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..fcc99550 --- /dev/null +++ b/docs/technical/api/scheduling/Api.Scheduling.md @@ -0,0 +1,297 @@ +# 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) + - [Get Scheduler Display Preferences](#get-scheduler-display-preferences) + - [Get Scheduler Display Preferences Request](#get-scheduler-display-preferences-request) + - [Get Scheduler Display Preferences Response](#get-scheduler-display-preferences-response) + - [Update Scheduler Display Preferences](#update-scheduler-display-preferences) + - [Update Scheduler Display Preferences Request](#update-scheduler-display-preferences-request) + - [Update Scheduler Display Preferences Response](#update-scheduler-display-preferences-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": "Active", + "lastStartedOnUtc": null, + "lastCompletedOnUtc": null +} +``` + +### Get Scheduler Display Preferences + +#### Get Scheduler Display Preferences Request + +```js +GET api/v1/scheduled-jobs/display-preferences +``` + +#### Get Scheduler Display Preferences Response + +```js +200 Ok +``` + +```json +{ + "userId": "2cff0c0f-3a67-4e30-b94f-f4e948a3b64f", + "jobTypeFilter": "ScanMediaLibraries", + "displayTimeSpan": 10, + "displayTimeUnit": "Minutes" +} +``` + +### Update Scheduler Display Preferences + +#### Update Scheduler Display Preferences Request + +```js +PUT api/v1/scheduled-jobs/display-preferences +``` + +```json +{ + "jobTypeFilter": "ScanMediaLibraries", + "displayTimeSpan": 10, + "displayTimeUnit": "Minutes" +} +``` + +#### Update Scheduler Display Preferences Response + +```js +200 Ok +``` + +### 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/GetSchedulerDisplayPreferences.http b/docs/technical/requests/scheduling/GetSchedulerDisplayPreferences.http new file mode 100644 index 00000000..99e15c76 --- /dev/null +++ b/docs/technical/requests/scheduling/GetSchedulerDisplayPreferences.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/scheduled-jobs/display-preferences +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/docs/technical/requests/scheduling/UpdateSchedulerDisplayPreferences.http b/docs/technical/requests/scheduling/UpdateSchedulerDisplayPreferences.http new file mode 100644 index 00000000..16d64d14 --- /dev/null +++ b/docs/technical/requests/scheduling/UpdateSchedulerDisplayPreferences.http @@ -0,0 +1,9 @@ +PUT {{host}}/api/v1/scheduled-jobs/display-preferences +Authorization: Bearer {{ACCESS_TOKEN}} +Content-Type: application/json + +{ + "jobTypeFilter": "ScanMediaLibraries", + "displayTimeSpan": 10, + "displayTimeUnit": "Minutes" +} diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/ScheduledJobEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/ScheduledJobEntity.cs new file mode 100644 index 00000000..5bf2c72d --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/ScheduledJobEntity.cs @@ -0,0 +1,90 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.Scheduling; + +/// +/// Repository entity for a scheduled job. +/// +[DebuggerDisplay("Id: {Id}, Status: {Status}")] +public class ScheduledJobEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets the Id of the scheduled job. + /// + public required Guid Id { get; init; } + + /// + /// Gets the name of the scheduled job. + /// + public required string Name { get; init; } + + /// + /// Gets the type of the task executed by the scheduled job. + /// + public required ScheduledTaskType TaskType { get; init; } + + /// + /// Gets the type of the schedule of the scheduled job. + /// + public required ScheduleType ScheduleType { get; init; } + + /// + /// Gets the interval in minutes of the schedule of the scheduled job, when its is . + /// + public int? IntervalMinutes { get; init; } + + /// + /// Gets the hour of the schedule of the scheduled job, when its is . + /// + public int? Hour { get; init; } + + /// + /// Gets the minute of the schedule of the scheduled job, when its is . + /// + public int? Minute { get; init; } + + /// + /// Gets the status of the scheduled job. + /// + public required ScheduledJobStatus Status { get; init; } + + /// + /// Gets the Id of the user that owns the scheduled job. + /// + public required Guid OwnerUserId { get; init; } + + /// + /// Gets the optional date and time when the task of the scheduled job last started its execution. + /// + public DateTime? LastStartedOnUtc { get; init; } + + /// + /// Gets the optional date and time when the task of the scheduled job last completed its execution. + /// + public DateTime? LastCompletedOnUtc { get; init; } + + /// + /// Gets or sets the time and date when the entity was added. + /// + public required DateTime CreatedOnUtc { get; set; } + + /// + /// Gets or sets the Id of the user that created the entity. + /// + public required Guid CreatedBy { get; set; } + + /// + /// Gets or sets the optional time and date when the entity was updated. + /// + public DateTime? UpdatedOnUtc { get; set; } + + /// + /// Gets or sets the optional Id of the user that updated the entity. + /// + public required Guid? UpdatedBy { get; set; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/ScheduledJobExecutionEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/ScheduledJobExecutionEntity.cs new file mode 100644 index 00000000..5bf05e66 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/ScheduledJobExecutionEntity.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.Scheduling; + +/// +/// Repository entity for an execution of the task of a scheduled job. +/// +[DebuggerDisplay("Id: {Id}, ScheduledJobId: {ScheduledJobId}")] +public class ScheduledJobExecutionEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets the Id of the execution of the task of a scheduled job. + /// + public required Guid Id { get; init; } + + /// + /// Gets the Id of the scheduled job whose task was executed. + /// + public required Guid ScheduledJobId { get; init; } + + /// + /// Gets the type of the task that was executed. + /// + public required ScheduledTaskType TaskType { get; init; } + + /// + /// Gets a value indicating whether the execution was triggered by the execution cycle of the scheduled job, or it was a one time execution. + /// + public required bool IsCycleRun { get; init; } + + /// + /// Gets the date and time when the execution started. + /// + public required DateTime StartedOnUtc { get; init; } + + /// + /// Gets the optional date and time when the execution completed. + /// + public DateTime? CompletedOnUtc { get; init; } + + /// + /// Gets a value indicating whether the execution cycle of the scheduled job was active when the execution started. + /// + /// + /// A job whose execution cycle is active stays in its active state while a manually fired one time execution runs, so an + /// interrupted execution of such a job must return it to its active state at the next startup; the flag keeps that fact + /// separate from , which records how the execution was triggered for the audit trail. + /// + public required bool WasCycleActive { get; init; } + + /// + /// Gets or sets the time and date when the entity was added. + /// + public required DateTime CreatedOnUtc { get; set; } + + /// + /// Gets or sets the Id of the user that created the entity. + /// + public required Guid CreatedBy { get; set; } + + /// + /// Gets or sets the optional time and date when the entity was updated. + /// + public DateTime? UpdatedOnUtc { get; set; } + + /// + /// Gets or sets the optional Id of the user that updated the entity. + /// + public required Guid? UpdatedBy { get; set; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/SchedulerDisplayPreferencesEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/SchedulerDisplayPreferencesEntity.cs new file mode 100644 index 00000000..7cdfea0d --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/SchedulerDisplayPreferencesEntity.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.Scheduling; + +/// +/// Repository entity for the display preferences of the scheduler page of a user. +/// +[DebuggerDisplay("UserId: {UserId}, DisplayTimeSpan: {DisplayTimeSpan}")] +public class SchedulerDisplayPreferencesEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets or sets the Id of the display preferences. + /// + public required Guid Id { get; init; } + + /// + /// Gets or sets the Id of the user that owns the display preferences. + /// + public required Guid UserId { get; set; } + + /// + /// Gets or sets the type of the scheduled job tasks whose executions are shown on the scheduler page, or when all of them are shown. + /// + public ScheduledTaskType? JobTypeFilter { get; set; } + + /// + /// Gets or sets the time span, expressed in , that the scheduler page shows. + /// + public required int DisplayTimeSpan { get; set; } + + /// + /// Gets or sets the unit in which the displayed time span of the scheduler page is expressed. + /// + public required SchedulerDisplayTimeUnit DisplayTimeUnit { get; set; } + + /// + /// Gets or sets the time and date when the entity was added. + /// + public required DateTime CreatedOnUtc { get; set; } + + /// + /// Gets or sets the Id of the user that created the entity. + /// + public required Guid CreatedBy { get; set; } + + /// + /// Gets or sets the optional time and date when the entity was updated. + /// + public DateTime? UpdatedOnUtc { get; set; } + + /// + /// Gets or sets the optional Id of the user that updated the entity. + /// + public required Guid? UpdatedBy { get; set; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/IScheduledJobExecutionRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/IScheduledJobExecutionRepository.cs new file mode 100644 index 00000000..a01a7f7e --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/IScheduledJobExecutionRepository.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; +using Lumina.Application.Common.DataAccess.Repositories.Common.Base; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.DataAccess.Repositories.Scheduling; + +/// +/// Interface for the repository for the executions of the tasks of scheduled jobs. +/// +public interface IScheduledJobExecutionRepository : IRepository, + IGetByIdRepositoryAction, + IInsertRepositoryAction, + IUpdateRepositoryAction +{ + /// + /// Gets the most recent execution of the task of a scheduled job identified by that is still running, from the storage medium. + /// + /// The Id of the scheduled job whose running execution is retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the running execution of the scheduled job, or . + Task> GetOpenByScheduledJobIdAsync(Guid scheduledJobId, CancellationToken cancellationToken); + + /// + /// Gets the executions of the tasks of scheduled jobs that started in the interval between and , from the storage medium. + /// + /// The inclusive lower bound of the interval, in UTC. + /// The inclusive upper bound of the interval, in UTC. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + Task>> GetByTimeRangeAsync(DateTime fromUtc, DateTime toUtc, CancellationToken cancellationToken); + + /// + /// Removes all the executions of the task of a scheduled job identified by , from the storage medium. + /// + /// The Id of the scheduled job whose executions are removed. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> DeleteByScheduledJobIdAsync(Guid scheduledJobId, CancellationToken cancellationToken); + + /// + /// Removes all the executions of the tasks of scheduled jobs that started before , from the storage medium. + /// + /// The exclusive lower bound of the retained interval, in UTC; executions that started before it are removed. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> DeleteOlderThanAsync(DateTime cutoffUtc, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/IScheduledJobRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/IScheduledJobRepository.cs new file mode 100644 index 00000000..84138240 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/IScheduledJobRepository.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; +using Lumina.Application.Common.DataAccess.Repositories.Common.Base; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.DataAccess.Repositories.Scheduling; + +/// +/// Interface for the repository for scheduled jobs. +/// +public interface IScheduledJobRepository : IRepository, + IGetByIdRepositoryAction, + IGetAllRepositoryAction, + IInsertRepositoryAction, + IUpdateRepositoryAction, + IDeleteByIdRepositoryAction +{ + /// + /// Gets a scheduled job identified by from the storage medium, without tracking it. + /// + /// The id of the scheduled job to get. + /// Cancellation token that can be used to stop the execution. + /// An containing either a identified by , or an error. + Task> GetByIdWithoutTrackingAsync(Guid id, CancellationToken cancellationToken); + + /// + /// Gets the scheduled jobs that have an active or running execution cycle, from the storage medium. + /// + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + Task>> GetActiveOrRunningAsync(CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/ISchedulerDisplayPreferencesRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/ISchedulerDisplayPreferencesRepository.cs new file mode 100644 index 00000000..c574e898 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/ISchedulerDisplayPreferencesRepository.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.Repositories.Common.Base; +using Lumina.Domain.Common.Primitives; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.DataAccess.Repositories.Scheduling; + +/// +/// Interface for the repository for the display preferences of the scheduler page. +/// +public interface ISchedulerDisplayPreferencesRepository : IRepository +{ + /// + /// Gets the display preferences of the scheduler page of the user identified by , if they exist. + /// + /// The Id of the user whose display preferences are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the display preferences of the user, or an error. + Task> GetByUserIdAsync(Guid userId, CancellationToken cancellationToken); + + /// + /// Inserts the display preferences of the scheduler page of a user, or updates them when they already exist. + /// + /// The display preferences to insert or update. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> UpsertAsync(SchedulerDisplayPreferencesEntity preferences, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/DataAccess/Seed/IDataSeedService.cs b/src/Lumina.Application/Common/DataAccess/Seed/IDataSeedService.cs index da3303cb..4314abbe 100644 --- a/src/Lumina.Application/Common/DataAccess/Seed/IDataSeedService.cs +++ b/src/Lumina.Application/Common/DataAccess/Seed/IDataSeedService.cs @@ -43,4 +43,12 @@ public interface IDataSeedService /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. Task> SetAdminRoleToAdministratorAccount(Guid userId, CancellationToken cancellationToken); + + /// + /// Sets up the default scheduled jobs, owned by the administrator account. + /// + /// The unique identifier of the administrator account that owns the default scheduled jobs. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> SetDefaultScheduledJobsAsync(Guid adminUserId, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs index f748d5dd..9c4c7407 100644 --- a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs +++ b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs @@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Repositories.Books; using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Themes; using Lumina.Application.Common.DataAccess.Repositories.Users; using System.Threading; @@ -87,6 +88,21 @@ public interface IUnitOfWork /// ILibraryBookReaderConfigurationRepository LibraryBookReaderConfigurationRepository { get; } + /// + /// Gets the scheduled job repository. + /// + IScheduledJobRepository ScheduledJobRepository { get; } + + /// + /// Gets the scheduled job execution repository. + /// + IScheduledJobExecutionRepository ScheduledJobExecutionRepository { get; } + + /// + /// Gets the scheduler display preferences repository. + /// + ISchedulerDisplayPreferencesRepository SchedulerDisplayPreferencesRepository { get; } + /// /// Gets the plugin repository. /// diff --git a/src/Lumina.Application/Common/Infrastructure/Scheduling/IScheduledJobScheduler.cs b/src/Lumina.Application/Common/Infrastructure/Scheduling/IScheduledJobScheduler.cs new file mode 100644 index 00000000..15828b20 --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Scheduling/IScheduledJobScheduler.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.Infrastructure.Scheduling; + +/// +/// Interface for the service that schedules and executes the tasks of scheduled jobs. +/// +public interface IScheduledJobScheduler +{ + /// + /// Starts the execution cycle of the scheduled job identified by . + /// + /// The object representing the unique identifier of the scheduled job whose execution cycle is started. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + Task StartCycleAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken); + + /// + /// Stops the execution cycle of the scheduled job identified by . + /// + /// The object representing the unique identifier of the scheduled job whose execution cycle is stopped. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + Task StopCycleAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken); + + /// + /// Fires the task of the scheduled job identified by once, without affecting its execution cycle. + /// + /// The object representing the unique identifier of the scheduled job whose task is fired. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + Task RunOnceAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/AddScheduledJobRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/AddScheduledJobRequestMapping.cs new file mode 100644 index 00000000..9bba28d0 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Scheduling/AddScheduledJobRequestMapping.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Scheduling.Commands.AddScheduledJob; +using Lumina.Contracts.Requests.Scheduling; +#endregion + +namespace Lumina.Application.Common.Mapping.Scheduling; + +/// +/// Extension methods for converting . +/// +public static class AddScheduledJobRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static AddScheduledJobCommand ToCommand(this AddScheduledJobRequest request) + { + return new AddScheduledJobCommand( + request.Name, + request.TaskType, + request.ScheduleType, + request.IntervalMinutes, + request.Hour, + request.Minute + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/FireScheduledJobRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/FireScheduledJobRequestMapping.cs new file mode 100644 index 00000000..d00d8df1 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Scheduling/FireScheduledJobRequestMapping.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Scheduling.Commands.FireScheduledJob; +using Lumina.Contracts.Requests.Scheduling; +#endregion + +namespace Lumina.Application.Common.Mapping.Scheduling; + +/// +/// Extension methods for converting . +/// +public static class FireScheduledJobRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static FireScheduledJobCommand ToCommand(this FireScheduledJobRequest request) + { + return new FireScheduledJobCommand( + request.ScheduledJobId + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/GetScheduledJobHistoryRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/GetScheduledJobHistoryRequestMapping.cs new file mode 100644 index 00000000..0a3ae563 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Scheduling/GetScheduledJobHistoryRequestMapping.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Scheduling.Queries.GetScheduledJobHistory; +using Lumina.Contracts.Requests.Scheduling; +#endregion + +namespace Lumina.Application.Common.Mapping.Scheduling; + +/// +/// Extension methods for converting . +/// +public static class GetScheduledJobHistoryRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetScheduledJobHistoryQuery ToQuery(this GetScheduledJobHistoryRequest request) + { + return new GetScheduledJobHistoryQuery( + request.From, + request.To + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/RemoveScheduledJobRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/RemoveScheduledJobRequestMapping.cs new file mode 100644 index 00000000..ea6432a9 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Scheduling/RemoveScheduledJobRequestMapping.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob; +using Lumina.Contracts.Requests.Scheduling; +#endregion + +namespace Lumina.Application.Common.Mapping.Scheduling; + +/// +/// Extension methods for converting . +/// +public static class RemoveScheduledJobRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static RemoveScheduledJobCommand ToCommand(this RemoveScheduledJobRequest request) + { + return new RemoveScheduledJobCommand( + request.ScheduledJobId + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobEntityMapping.cs new file mode 100644 index 00000000..23734cb6 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobEntityMapping.cs @@ -0,0 +1,110 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.Scheduling; + +/// +/// Extension methods for converting . +/// +public static class ScheduledJobEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// + /// An containing either a converted , or an error message. + /// + public static Result ToDomainEntity(this ScheduledJobEntity repositoryEntity) + { + Result scheduleResult = CreateSchedule(repositoryEntity); + if (scheduleResult.IsFailure) + return scheduleResult.Errors; + + return ScheduledJob.Create( + ScheduledJobId.Create(repositoryEntity.Id), + repositoryEntity.Name, + repositoryEntity.TaskType, + scheduleResult.Value, + UserId.Create(repositoryEntity.OwnerUserId), + repositoryEntity.Status, + Optional.FromNullable(repositoryEntity.LastStartedOnUtc), + Optional.FromNullable(repositoryEntity.LastCompletedOnUtc) + ); + } + + /// + /// Converts to a collection of . + /// + /// The repository entities to be converted. + /// + /// An containing either a collection of converted , or an error message. + /// + public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) + { + return repositoryEntities.Select(repositoryEntity => repositoryEntity.ToDomainEntity()); + } + + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted scheduled job response. + public static ScheduledJobResponse ToResponse(this ScheduledJobEntity repositoryEntity) + { + return new ScheduledJobResponse( + repositoryEntity.Id, + repositoryEntity.Name, + repositoryEntity.TaskType, + repositoryEntity.ScheduleType, + repositoryEntity.IntervalMinutes, + repositoryEntity.Hour, + repositoryEntity.Minute, + repositoryEntity.Status, + repositoryEntity.LastStartedOnUtc, + repositoryEntity.LastCompletedOnUtc + ); + } + + /// + /// Creates the schedule of from its flattened schedule properties. + /// + /// The repository entity whose schedule is created. + /// + /// An containing either a created , or an error message. + /// + private static Result CreateSchedule(ScheduledJobEntity repositoryEntity) + { + if (repositoryEntity.ScheduleType == ScheduleType.WithIntervalInMinutes) + { + Result intervalScheduleResult = IntervalSchedule.Create(repositoryEntity.IntervalMinutes ?? 0); + if (intervalScheduleResult.IsFailure) + return intervalScheduleResult.Errors; + return Result.From(intervalScheduleResult.Value); + } + + if (repositoryEntity.ScheduleType == ScheduleType.OnceAtStartup) + { + Result onceAtStartupScheduleResult = OnceAtStartupSchedule.Create(); + if (onceAtStartupScheduleResult.IsFailure) + return onceAtStartupScheduleResult.Errors; + return Result.From(onceAtStartupScheduleResult.Value); + } + + Result dailyScheduleResult = DailySchedule.Create(repositoryEntity.Hour ?? 0, repositoryEntity.Minute ?? 0); + if (dailyScheduleResult.IsFailure) + return dailyScheduleResult.Errors; + return Result.From(dailyScheduleResult.Value); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobExecutionEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobExecutionEntityMapping.cs new file mode 100644 index 00000000..2ac77c66 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobExecutionEntityMapping.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +#endregion + +namespace Lumina.Application.Common.Mapping.Scheduling; + +/// +/// Extension methods for converting . +/// +public static class ScheduledJobExecutionEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted execution response. + public static ScheduledJobExecutionResponse ToResponse(this ScheduledJobExecutionEntity repositoryEntity) + { + return new ScheduledJobExecutionResponse( + repositoryEntity.Id, + repositoryEntity.ScheduledJobId, + repositoryEntity.TaskType, + repositoryEntity.IsCycleRun, + repositoryEntity.StartedOnUtc, + repositoryEntity.CompletedOnUtc + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobMapping.cs new file mode 100644 index 00000000..3099ea14 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobMapping.cs @@ -0,0 +1,93 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using System; +#endregion + +namespace Lumina.Application.Common.Mapping.Scheduling; + +/// +/// Extension methods for converting . +/// +public static class ScheduledJobMapping +{ + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted repository entity. + public static ScheduledJobEntity ToRepositoryEntity(this ScheduledJob domainEntity) + { + return new ScheduledJobEntity + { + Id = domainEntity.Id.Value, + Name = domainEntity.Name, + TaskType = domainEntity.TaskType, + ScheduleType = domainEntity.Schedule.ScheduleType, + IntervalMinutes = GetIntervalMinutes(domainEntity), + Hour = GetHour(domainEntity), + Minute = GetMinute(domainEntity), + Status = domainEntity.Status, + OwnerUserId = domainEntity.OwnerUserId.Value, + LastStartedOnUtc = domainEntity.LastStartedOnUtc.HasValue ? domainEntity.LastStartedOnUtc.Value : null, + LastCompletedOnUtc = domainEntity.LastCompletedOnUtc.HasValue ? domainEntity.LastCompletedOnUtc.Value : null, + CreatedOnUtc = domainEntity.CreatedOnUtc, + CreatedBy = Guid.Empty, + UpdatedOnUtc = domainEntity.UpdatedOnUtc, + UpdatedBy = Guid.Empty + }; + } + + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted scheduled job response. + public static ScheduledJobResponse ToResponse(this ScheduledJob domainEntity) + { + return new ScheduledJobResponse( + domainEntity.Id.Value, + domainEntity.Name, + domainEntity.TaskType, + domainEntity.Schedule.ScheduleType, + GetIntervalMinutes(domainEntity), + GetHour(domainEntity), + GetMinute(domainEntity), + domainEntity.Status, + domainEntity.LastStartedOnUtc.HasValue ? domainEntity.LastStartedOnUtc.Value : null, + domainEntity.LastCompletedOnUtc.HasValue ? domainEntity.LastCompletedOnUtc.Value : null + ); + } + + /// + /// Gets the interval in minutes of the schedule of , when it is an interval schedule. + /// + /// The scheduled job whose schedule interval is retrieved. + /// The interval in minutes of the schedule, or when the schedule is not an interval schedule. + private static int? GetIntervalMinutes(ScheduledJob domainEntity) + { + return domainEntity.Schedule is IntervalSchedule intervalSchedule ? intervalSchedule.IntervalMinutes : null; + } + + /// + /// Gets the hour of the schedule of , when it is a daily schedule. + /// + /// The scheduled job whose schedule hour is retrieved. + /// The hour of the schedule, or when the schedule is not a daily schedule. + private static int? GetHour(ScheduledJob domainEntity) + { + return domainEntity.Schedule is DailySchedule dailySchedule ? dailySchedule.Hour : null; + } + + /// + /// Gets the minute of the schedule of , when it is a daily schedule. + /// + /// The scheduled job whose schedule minute is retrieved. + /// The minute of the schedule, or when the schedule is not a daily schedule. + private static int? GetMinute(ScheduledJob domainEntity) + { + return domainEntity.Schedule is DailySchedule dailySchedule ? dailySchedule.Minute : null; + } +} diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/SchedulerDisplayPreferencesEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/SchedulerDisplayPreferencesEntityMapping.cs new file mode 100644 index 00000000..0e01d898 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Scheduling/SchedulerDisplayPreferencesEntityMapping.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +#endregion + +namespace Lumina.Application.Common.Mapping.Scheduling; + +/// +/// Extension methods for converting . +/// +public static class SchedulerDisplayPreferencesEntityMapping +{ + private const int DEFAULT_DISPLAY_TIME_SPAN = 10; + private const SchedulerDisplayTimeUnit DEFAULT_DISPLAY_TIME_UNIT = SchedulerDisplayTimeUnit.Minutes; + + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted response. + public static SchedulerDisplayPreferencesResponse ToResponse(this SchedulerDisplayPreferencesEntity repositoryEntity) + { + return new SchedulerDisplayPreferencesResponse( + repositoryEntity.UserId, + repositoryEntity.JobTypeFilter, + repositoryEntity.DisplayTimeSpan, + repositoryEntity.DisplayTimeUnit + ); + } + + /// + /// Converts the lack of stored display preferences to the default of the user identified by . + /// + /// The missing repository entity, which is . + /// The Id of the user that owns the display preferences. + /// The converted response with the default display preferences. + public static SchedulerDisplayPreferencesResponse ToDefaultResponse(this SchedulerDisplayPreferencesEntity? repositoryEntity, Guid userId) + { + return new SchedulerDisplayPreferencesResponse( + userId, + null, + DEFAULT_DISPLAY_TIME_SPAN, + DEFAULT_DISPLAY_TIME_UNIT + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/StartScheduledJobRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/StartScheduledJobRequestMapping.cs new file mode 100644 index 00000000..067665ec --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Scheduling/StartScheduledJobRequestMapping.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Scheduling.Commands.StartScheduledJob; +using Lumina.Contracts.Requests.Scheduling; +#endregion + +namespace Lumina.Application.Common.Mapping.Scheduling; + +/// +/// Extension methods for converting . +/// +public static class StartScheduledJobRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static StartScheduledJobCommand ToCommand(this StartScheduledJobRequest request) + { + return new StartScheduledJobCommand( + request.ScheduledJobId + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/StopScheduledJobRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/StopScheduledJobRequestMapping.cs new file mode 100644 index 00000000..488a699a --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Scheduling/StopScheduledJobRequestMapping.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Scheduling.Commands.StopScheduledJob; +using Lumina.Contracts.Requests.Scheduling; +#endregion + +namespace Lumina.Application.Common.Mapping.Scheduling; + +/// +/// Extension methods for converting . +/// +public static class StopScheduledJobRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static StopScheduledJobCommand ToCommand(this StopScheduledJobRequest request) + { + return new StopScheduledJobCommand( + request.ScheduledJobId + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/UpdateSchedulerDisplayPreferencesRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/UpdateSchedulerDisplayPreferencesRequestMapping.cs new file mode 100644 index 00000000..f0e74408 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Scheduling/UpdateSchedulerDisplayPreferencesRequestMapping.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences; +using Lumina.Contracts.Requests.Scheduling; +#endregion + +namespace Lumina.Application.Common.Mapping.Scheduling; + +/// +/// Extension methods for converting . +/// +public static class UpdateSchedulerDisplayPreferencesRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static UpdateSchedulerDisplayPreferencesCommand ToCommand(this UpdateSchedulerDisplayPreferencesRequest request) + { + return new UpdateSchedulerDisplayPreferencesCommand( + request.JobTypeFilter, + request.DisplayTimeSpan, + request.DisplayTimeUnit + ); + } +} diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs index fdc1df53..47a8a836 100644 --- a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs @@ -1,16 +1,21 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.Seed; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DomainEvents; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Contracts.Responses.Authentication; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; using System; using System.Collections.Generic; using System.Linq; @@ -32,6 +37,7 @@ public class SetupApplicationCommandHandler : ICommandHandler _validator; /// @@ -44,6 +50,7 @@ public class SetupApplicationCommandHandler : ICommandHandlerInjected service for generating QR codes. /// Injected service for time related concerns. /// Injected service for the initial persistence medium data seed. + /// Injected service for the queue of domain events. /// Injected validator for application validation rules. public SetupApplicationCommandHandler( IUnitOfWork unitOfWork, @@ -53,6 +60,7 @@ public class SetupApplicationCommandHandler : ICommandHandler validator) { _unitOfWork = unitOfWork; @@ -62,6 +70,7 @@ public class SetupApplicationCommandHandler : ICommandHandler 0) return validationResult; - // check if any users already exists (admin account is only set once!) + // Check if any users already exists (admin account is only set once!). Result> selectUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); if (selectUsersResult.IsFailure) return selectUsersResult.Errors; @@ -100,23 +109,23 @@ public class SetupApplicationCommandHandler : ICommandHandler insertUserResult = await _unitOfWork.UserRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false); if (insertUserResult.IsFailure) return insertUserResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - // set the default permissions, roles, roles permissions + // Set the default permissions, roles, roles permissions. Result setPermissionsResult = await _dataSeedService.SetDefaultAuthorizationPermissionsAsync(id, cancellationToken).ConfigureAwait(false); if (setPermissionsResult.IsFailure) return setPermissionsResult.Errors; @@ -133,8 +142,23 @@ public class SetupApplicationCommandHandler : ICommandHandler setDefaultScheduledJobsResult = await _dataSeedService.SetDefaultScheduledJobsAsync(id, cancellationToken).ConfigureAwait(false); + if (setDefaultScheduledJobsResult.IsFailure) + return setDefaultScheduledJobsResult.Errors; + + // The default jobs were seeded with an active execution cycle, so a cycle started event is queued for each of them; the + // queued events are published only after the setup transaction commits, because a cycle worker started inside the request + // would try to read the scheduled jobs while the still open setup transaction locks the storage medium. + Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + if (getScheduledJobsResult.IsFailure) + return getScheduledJobsResult.Errors; + foreach (ScheduledJobEntity scheduledJob in getScheduledJobsResult.Value) + if (scheduledJob.Status == ScheduledJobStatus.Active) + _domainEventsQueue.Enqueue(new ScheduledJobCycleStartedDomainEvent(Guid.NewGuid(), ScheduledJobId.Create(scheduledJob.Id), DateTime.UtcNow)); + + // TODO: insert the default admin profile preferences when they are implemented. + // If 2FA was enabled during registration, the TOTP secret needs to be delivered to the client unhashed, so it can be displayed return new RegistrationResponse(user.Id, user.Username, totpSecret); } } diff --git a/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommand.cs b/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommand.cs new file mode 100644 index 00000000..becfb43d --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommand.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Scheduling.Commands.AddScheduledJob; + +/// +/// Command for adding a scheduled job. +/// +/// The name of the scheduled job. +/// The type of the task executed by the scheduled job. +/// The type of the schedule of the scheduled job. +/// The interval in minutes of the schedule, when the schedule type is . +/// The hour of the schedule, when the schedule type is . +/// The minute of the schedule, when the schedule type is . +[DebuggerDisplay("Name: {Name}")] +public record AddScheduledJobCommand( + string Name, + ScheduledTaskType TaskType, + ScheduleType ScheduleType, + int? IntervalMinutes, + int? Hour, + int? Minute +) : ICommand; diff --git a/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandler.cs new file mode 100644 index 00000000..02151efa --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandler.cs @@ -0,0 +1,129 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DomainEvents; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Scheduling.Commands.AddScheduledJob; + +/// +/// Handler for the command to add a scheduled job. +/// +public class AddScheduledJobCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IDomainEventsQueue _domainEventsQueue; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected service for the queue of domain events. + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. + public AddScheduledJobCommandHandler( + IAuthorizationService authorizationService, + ICurrentUserService currentUserService, + IDomainEventsQueue domainEventsQueue, + IUnitOfWork unitOfWork, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _domainEventsQueue = domainEventsQueue; + _validator = validator; + } + + /// + /// Handles the command to add a scheduled job. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully created , or an error message. + /// + public async Task> HandleAsync(AddScheduledJobCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // Only administrators can schedule jobs. + if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false)) + return ApplicationErrors.Authorization.NotAuthorized; + + // Create the schedule of the scheduled job, based on its type. + Result scheduleResult; + if (command.ScheduleType == ScheduleType.WithIntervalInMinutes) + { + Result intervalScheduleResult = IntervalSchedule.Create(command.IntervalMinutes ?? 0); + if (intervalScheduleResult.IsFailure) + return intervalScheduleResult.Errors; + scheduleResult = Result.From(intervalScheduleResult.Value); + } + else if (command.ScheduleType == ScheduleType.DailyAtHourAndMinute) + { + Result dailyScheduleResult = DailySchedule.Create(command.Hour ?? 0, command.Minute ?? 0); + if (dailyScheduleResult.IsFailure) + return dailyScheduleResult.Errors; + scheduleResult = Result.From(dailyScheduleResult.Value); + } + else if (command.ScheduleType == ScheduleType.OnceAtStartup) + { + Result onceAtStartupScheduleResult = OnceAtStartupSchedule.Create(); + if (onceAtStartupScheduleResult.IsFailure) + return onceAtStartupScheduleResult.Errors; + scheduleResult = Result.From(onceAtStartupScheduleResult.Value); + } + else + return DomainErrors.Scheduling.InvalidScheduleType; + + // Create a domain scheduled job object. + Result createScheduledJobResult = ScheduledJob.Create(command.Name, command.TaskType, scheduleResult.Value, UserId.Create(userId)); + if (createScheduledJobResult.IsFailure) + return createScheduledJobResult.Errors; + createScheduledJobResult.Value.Add(); + + // Convert the domain scheduled job to a repository entity, insert it, and save the changes. + ScheduledJobEntity persistenceScheduledJob = createScheduledJobResult.Value.ToRepositoryEntity(); + Result insertScheduledJobResult = await _unitOfWork.ScheduledJobRepository.InsertAsync(persistenceScheduledJob, cancellationToken).ConfigureAwait(false); + if (insertScheduledJobResult.IsFailure) + return insertScheduledJobResult.Errors; + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + // Queue any domain events. + foreach (IDomainEvent domainEvent in createScheduledJobResult.Value.GetDomainEvents()) + _domainEventsQueue.Enqueue(domainEvent); + + return createScheduledJobResult.Value.ToResponse(); + } +} diff --git a/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandValidator.cs b/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandValidator.cs new file mode 100644 index 00000000..04a30b31 --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandValidator.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +#endregion + +namespace Lumina.Application.Core.Scheduling.Commands.AddScheduledJob; + +/// +/// Validates the needed validation rules for . +/// +public class AddScheduledJobCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public AddScheduledJobCommandValidator() + { + RuleFor(command => command.Name) + .NotEmpty() + .WithError(Errors.Scheduling.ScheduledJobNameCannotBeEmpty) + .MaximumLength(80) + .WithError(Errors.Scheduling.ScheduledJobNameCannotBeEmpty); + + RuleFor(command => command.TaskType) + .IsInEnum() + .WithError(Errors.Scheduling.InvalidScheduleType); + + RuleFor(command => command.ScheduleType) + .IsInEnum() + .WithError(Errors.Scheduling.InvalidScheduleType); + + RuleFor(command => command.IntervalMinutes) + .Must(intervalMinutes => intervalMinutes is null || intervalMinutes > 0) + .WithError(Errors.Scheduling.IntervalMinutesMustBePositive) + .When(command => command.ScheduleType == ScheduleType.WithIntervalInMinutes); + + RuleFor(command => command.IntervalMinutes) + .Must(intervalMinutes => intervalMinutes is not null) + .WithError(Errors.Scheduling.IntervalMinutesMustBePositive) + .When(command => command.ScheduleType == ScheduleType.WithIntervalInMinutes); + + RuleFor(command => command.Hour) + .Must(hour => hour is not null) + .WithError(Errors.Scheduling.HourMustBeBetweenZeroAndTwentyThree) + .When(command => command.ScheduleType == ScheduleType.DailyAtHourAndMinute); + + RuleFor(command => command.Minute) + .Must(minute => minute is not null) + .WithError(Errors.Scheduling.MinuteMustBeBetweenZeroAndFiftyNine) + .When(command => command.ScheduleType == ScheduleType.DailyAtHourAndMinute); + + RuleFor(command => command.Hour) + .InclusiveBetween(0, 23) + .WithError(Errors.Scheduling.HourMustBeBetweenZeroAndTwentyThree) + .When(command => command.ScheduleType == ScheduleType.DailyAtHourAndMinute); + + RuleFor(command => command.Minute) + .InclusiveBetween(0, 59) + .WithError(Errors.Scheduling.MinuteMustBeBetweenZeroAndFiftyNine) + .When(command => command.ScheduleType == ScheduleType.DailyAtHourAndMinute); + } +} diff --git a/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommand.cs b/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommand.cs new file mode 100644 index 00000000..f10430d1 --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommand.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Scheduling.Commands.FireScheduledJob; + +/// +/// Command for firing the task of a scheduled job once, without affecting its execution cycle. +/// +/// The unique identifier of the scheduled job whose task is fired. +[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")] +public record FireScheduledJobCommand( + Guid ScheduledJobId +) : ICommand; diff --git a/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandHandler.cs new file mode 100644 index 00000000..86585082 --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandHandler.cs @@ -0,0 +1,102 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DomainEvents; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Scheduling.Commands.FireScheduledJob; + +/// +/// Handler for the command to fire the task of a scheduled job once. +/// +public class FireScheduledJobCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IDomainEventsQueue _domainEventsQueue; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected service for the queue of domain events. + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. + public FireScheduledJobCommandHandler( + IAuthorizationService authorizationService, + ICurrentUserService currentUserService, + IDomainEventsQueue domainEventsQueue, + IUnitOfWork unitOfWork, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _domainEventsQueue = domainEventsQueue; + _validator = validator; + } + + /// + /// Handles the command to fire the task of a scheduled job once. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a , or an error message. + /// + public async Task> HandleAsync(FireScheduledJobCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // Only administrators can fire scheduled jobs. + if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false)) + return ApplicationErrors.Authorization.NotAuthorized; + + // Get the scheduled job from the storage medium. + Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false); + if (getScheduledJobResult.IsFailure) + return getScheduledJobResult.Errors; + if (getScheduledJobResult.Value is null) + return DomainErrors.Scheduling.ScheduledJobNotFound; + + // Convert the repository entity to a domain entity, and guard the fire against a currently running task. + Result scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity(); + if (scheduledJobDomainResult.IsFailure) + return scheduledJobDomainResult.Errors; + Result fireResult = scheduledJobDomainResult.Value.Fire(); + if (fireResult.IsFailure) + return fireResult.Errors; + + // Queue the domain event that requests a one time execution of the task of the scheduled job. + foreach (IDomainEvent domainEvent in scheduledJobDomainResult.Value.GetDomainEvents()) + _domainEventsQueue.Enqueue(domainEvent); + + return scheduledJobDomainResult.Value.ToResponse(); + } +} diff --git a/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandValidator.cs b/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandValidator.cs new file mode 100644 index 00000000..425b31ee --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandValidator.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +#endregion + +namespace Lumina.Application.Core.Scheduling.Commands.FireScheduledJob; + +/// +/// Validates the needed validation rules for . +/// +public class FireScheduledJobCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public FireScheduledJobCommandValidator() + { + RuleFor(command => command.ScheduledJobId) + .NotEmpty() + .WithError(Errors.Scheduling.ScheduledJobNotFound); + } +} diff --git a/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommand.cs b/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommand.cs new file mode 100644 index 00000000..ff0e74c8 --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommand.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob; + +/// +/// Command for removing a scheduled job. +/// +/// The unique identifier of the scheduled job to remove. +[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")] +public record RemoveScheduledJobCommand( + Guid ScheduledJobId +) : ICommand; diff --git a/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandler.cs new file mode 100644 index 00000000..ba19721c --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandler.cs @@ -0,0 +1,114 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DomainEvents; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Scheduling; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob; + +/// +/// Handler for the command to remove a scheduled job. +/// +public class RemoveScheduledJobCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IDomainEventsQueue _domainEventsQueue; + private readonly IScheduledJobScheduler _scheduledJobScheduler; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected service for the queue of domain events. + /// Injected service that schedules and executes the tasks of scheduled jobs. + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. + public RemoveScheduledJobCommandHandler( + IAuthorizationService authorizationService, + ICurrentUserService currentUserService, + IDomainEventsQueue domainEventsQueue, + IScheduledJobScheduler scheduledJobScheduler, + IUnitOfWork unitOfWork, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _domainEventsQueue = domainEventsQueue; + _scheduledJobScheduler = scheduledJobScheduler; + _validator = validator; + } + + /// + /// Handles the command to remove a scheduled job. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An representing either a successful operation, or an error. + /// + public async Task> HandleAsync(RemoveScheduledJobCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // Only administrators can remove scheduled jobs. + if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false)) + return ApplicationErrors.Authorization.NotAuthorized; + + // Get the scheduled job from the storage medium. + Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false); + if (getScheduledJobResult.IsFailure) + return getScheduledJobResult.Errors; + if (getScheduledJobResult.Value is null) + return DomainErrors.Scheduling.ScheduledJobNotFound; + + // Stop the execution cycle of the scheduled job, if it has one. + Result scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity(); + if (scheduledJobDomainResult.IsFailure) + return scheduledJobDomainResult.Errors; + await _scheduledJobScheduler.StopCycleAsync(scheduledJobDomainResult.Value.Id, cancellationToken).ConfigureAwait(false); + + // Remove the executions and the scheduled job itself from the storage medium. + Result deleteExecutionsResult = await _unitOfWork.ScheduledJobExecutionRepository.DeleteByScheduledJobIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false); + if (deleteExecutionsResult.IsFailure) + return deleteExecutionsResult.Errors; + Result deleteScheduledJobResult = await _unitOfWork.ScheduledJobRepository.DeleteByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false); + if (deleteScheduledJobResult.IsFailure) + return deleteScheduledJobResult.Errors; + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + // Queue any domain events. + scheduledJobDomainResult.Value.Remove(); + foreach (IDomainEvent domainEvent in scheduledJobDomainResult.Value.GetDomainEvents()) + _domainEventsQueue.Enqueue(domainEvent); + + return Result.Success; + } +} diff --git a/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandValidator.cs b/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandValidator.cs new file mode 100644 index 00000000..8980ee94 --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandValidator.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +#endregion + +namespace Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob; + +/// +/// Validates the needed validation rules for . +/// +public class RemoveScheduledJobCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public RemoveScheduledJobCommandValidator() + { + RuleFor(command => command.ScheduledJobId) + .NotEmpty() + .WithError(Errors.Scheduling.ScheduledJobNotFound); + } +} diff --git a/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommand.cs b/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommand.cs new file mode 100644 index 00000000..14b8203b --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommand.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Scheduling.Commands.StartScheduledJob; + +/// +/// Command for starting the execution cycle of a scheduled job. +/// +/// The unique identifier of the scheduled job whose execution cycle is started. +[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")] +public record StartScheduledJobCommand( + Guid ScheduledJobId +) : ICommand; diff --git a/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandler.cs new file mode 100644 index 00000000..f5c0be2f --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandler.cs @@ -0,0 +1,109 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DomainEvents; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Scheduling.Commands.StartScheduledJob; + +/// +/// Handler for the command to start the execution cycle of a scheduled job. +/// +public class StartScheduledJobCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IDomainEventsQueue _domainEventsQueue; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected service for the queue of domain events. + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. + public StartScheduledJobCommandHandler( + IAuthorizationService authorizationService, + ICurrentUserService currentUserService, + IDomainEventsQueue domainEventsQueue, + IUnitOfWork unitOfWork, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _domainEventsQueue = domainEventsQueue; + _validator = validator; + } + + /// + /// Handles the command to start the execution cycle of a scheduled job. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a , or an error message. + /// + public async Task> HandleAsync(StartScheduledJobCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // Only administrators can start scheduled jobs. + if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false)) + return ApplicationErrors.Authorization.NotAuthorized; + + // Get the scheduled job from the storage medium. + Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false); + if (getScheduledJobResult.IsFailure) + return getScheduledJobResult.Errors; + if (getScheduledJobResult.Value is null) + return DomainErrors.Scheduling.ScheduledJobNotFound; + + // Convert the repository entity to a domain entity, and start its execution cycle. + Result scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity(); + if (scheduledJobDomainResult.IsFailure) + return scheduledJobDomainResult.Errors; + Result startCycleResult = scheduledJobDomainResult.Value.StartCycle(); + if (startCycleResult.IsFailure) + return startCycleResult.Errors; + + // Persist the new status of the scheduled job. + Result updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(scheduledJobDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (updateScheduledJobResult.IsFailure) + return updateScheduledJobResult.Errors; + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + // Queue any domain events. + foreach (IDomainEvent domainEvent in scheduledJobDomainResult.Value.GetDomainEvents()) + _domainEventsQueue.Enqueue(domainEvent); + + return scheduledJobDomainResult.Value.ToResponse(); + } +} diff --git a/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandValidator.cs b/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandValidator.cs new file mode 100644 index 00000000..2b09e00b --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandValidator.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +#endregion + +namespace Lumina.Application.Core.Scheduling.Commands.StartScheduledJob; + +/// +/// Validates the needed validation rules for . +/// +public class StartScheduledJobCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public StartScheduledJobCommandValidator() + { + RuleFor(command => command.ScheduledJobId) + .NotEmpty() + .WithError(Errors.Scheduling.ScheduledJobNotFound); + } +} diff --git a/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommand.cs b/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommand.cs new file mode 100644 index 00000000..2ee36eed --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommand.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Scheduling.Commands.StopScheduledJob; + +/// +/// Command for stopping the execution cycle of a scheduled job. +/// +/// The unique identifier of the scheduled job whose execution cycle is stopped. +[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")] +public record StopScheduledJobCommand( + Guid ScheduledJobId +) : ICommand; diff --git a/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandler.cs new file mode 100644 index 00000000..177e0865 --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandler.cs @@ -0,0 +1,116 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DomainEvents; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Scheduling; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Scheduling.Commands.StopScheduledJob; + +/// +/// Handler for the command to stop the execution cycle of a scheduled job. +/// +public class StopScheduledJobCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IDomainEventsQueue _domainEventsQueue; + private readonly IScheduledJobScheduler _scheduledJobScheduler; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected service for the queue of domain events. + /// Injected service that schedules and executes the tasks of scheduled jobs. + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. + public StopScheduledJobCommandHandler( + IAuthorizationService authorizationService, + ICurrentUserService currentUserService, + IDomainEventsQueue domainEventsQueue, + IScheduledJobScheduler scheduledJobScheduler, + IUnitOfWork unitOfWork, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _domainEventsQueue = domainEventsQueue; + _scheduledJobScheduler = scheduledJobScheduler; + _validator = validator; + } + + /// + /// Handles the command to stop the execution cycle of a scheduled job. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a , or an error message. + /// + public async Task> HandleAsync(StopScheduledJobCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // Only administrators can stop scheduled jobs. + if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false)) + return ApplicationErrors.Authorization.NotAuthorized; + + // Get the scheduled job from the storage medium. + Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false); + if (getScheduledJobResult.IsFailure) + return getScheduledJobResult.Errors; + if (getScheduledJobResult.Value is null) + return DomainErrors.Scheduling.ScheduledJobNotFound; + + // Convert the repository entity to a domain entity, and stop its execution cycle. + Result scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity(); + if (scheduledJobDomainResult.IsFailure) + return scheduledJobDomainResult.Errors; + Result stopCycleResult = scheduledJobDomainResult.Value.StopCycle(); + if (stopCycleResult.IsFailure) + return stopCycleResult.Errors; + + // Persist the new status of the scheduled job. + Result updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(scheduledJobDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (updateScheduledJobResult.IsFailure) + return updateScheduledJobResult.Errors; + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + // Stop the execution cycle in the scheduler service. + await _scheduledJobScheduler.StopCycleAsync(scheduledJobDomainResult.Value.Id, cancellationToken).ConfigureAwait(false); + + // Queue any domain events. + foreach (IDomainEvent domainEvent in scheduledJobDomainResult.Value.GetDomainEvents()) + _domainEventsQueue.Enqueue(domainEvent); + + return scheduledJobDomainResult.Value.ToResponse(); + } +} diff --git a/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandValidator.cs b/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandValidator.cs new file mode 100644 index 00000000..03681f46 --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandValidator.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +#endregion + +namespace Lumina.Application.Core.Scheduling.Commands.StopScheduledJob; + +/// +/// Validates the needed validation rules for . +/// +public class StopScheduledJobCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public StopScheduledJobCommandValidator() + { + RuleFor(command => command.ScheduledJobId) + .NotEmpty() + .WithError(Errors.Scheduling.ScheduledJobNotFound); + } +} diff --git a/src/Lumina.Application/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommand.cs b/src/Lumina.Application/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommand.cs new file mode 100644 index 00000000..2115f817 --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommand.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences; + +/// +/// Command for updating the display preferences of the scheduler page of the current user. +/// +/// The type of the scheduled job tasks whose executions are shown on the scheduler page, or when all of them are shown. +/// The time span, expressed in , that the scheduler page shows. +/// The unit in which the displayed time span of the scheduler page is expressed. +[DebuggerDisplay("DisplayTimeSpan: {DisplayTimeSpan} {DisplayTimeUnit}")] +public record UpdateSchedulerDisplayPreferencesCommand( + ScheduledTaskType? JobTypeFilter, + int DisplayTimeSpan, + SchedulerDisplayTimeUnit DisplayTimeUnit +) : ICommand; diff --git a/src/Lumina.Application/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandHandler.cs new file mode 100644 index 00000000..54c6fa4b --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandHandler.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences; + +/// +/// Handler for the command to update the display preferences of the scheduler page of the current user. +/// +public class UpdateSchedulerDisplayPreferencesCommandHandler : ICommandHandler> +{ + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IUnitOfWork _unitOfWork; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. + public UpdateSchedulerDisplayPreferencesCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) + { + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _unitOfWork = unitOfWork; + _validator = validator; + } + + /// + /// Handles the command to update the display preferences of the scheduler page of the current user. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An representing either a successful update, or an error. + /// + public async Task> HandleAsync(UpdateSchedulerDisplayPreferencesCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // Only administrators can use the scheduler page. + if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false)) + return ApplicationErrors.Authorization.NotAuthorized; + + // Upsert the display preferences of the scheduler page of the current user. + SchedulerDisplayPreferencesEntity displayPreferences = new() + { + Id = Guid.NewGuid(), + UserId = userId, + JobTypeFilter = command.JobTypeFilter, + DisplayTimeSpan = command.DisplayTimeSpan, + DisplayTimeUnit = command.DisplayTimeUnit, + CreatedOnUtc = default, + CreatedBy = default, + UpdatedOnUtc = null, + UpdatedBy = null + }; + Result upsertResult = await _unitOfWork.SchedulerDisplayPreferencesRepository.UpsertAsync(displayPreferences, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsFailure) + return upsertResult.Errors; + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + return Result.Updated; + } +} diff --git a/src/Lumina.Application/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandValidator.cs b/src/Lumina.Application/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandValidator.cs new file mode 100644 index 00000000..6dea97e1 --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandValidator.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +#endregion + +namespace Lumina.Application.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences; + +/// +/// Validates the needed validation rules for . +/// +public class UpdateSchedulerDisplayPreferencesCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateSchedulerDisplayPreferencesCommandValidator() + { + RuleFor(command => command.DisplayTimeSpan) + .GreaterThan(0) + .WithError(Errors.Scheduling.SchedulerDisplayTimeSpanMustBePositive); + } +} diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobAddedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobAddedDomainEventHandler.cs new file mode 100644 index 00000000..4a523bd2 --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobAddedDomainEventHandler.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Application.Core.Scheduling.Notifications; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Exceptions; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.Scheduling.Events; + +/// +/// Handler for the domain event raised when a scheduled job is added. +/// +public class ScheduledJobAddedDomainEventHandler : IDomainEventHandler +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IScheduledJobNotifier _scheduledJobNotifier; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for notifying the scheduled job changes to SignalR clients. + /// Injected unit of work for interacting with the data access layer repositories. + public ScheduledJobAddedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + _scheduledJobNotifier = scheduledJobNotifier; + } + + /// + /// Handles the event raised when a scheduled job is added. + /// + /// The domain event to be handled. + /// Cancellation token that can be used to stop the execution. + public async ValueTask HandleAsync(ScheduledJobAddedDomainEvent domainEvent, CancellationToken cancellationToken) + { + Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + if (getScheduledJobsResult.IsFailure) + throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors); + IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())]; + await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobCycleStartedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobCycleStartedDomainEventHandler.cs new file mode 100644 index 00000000..974f02ed --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobCycleStartedDomainEventHandler.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Scheduling; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Application.Core.Scheduling.Notifications; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Exceptions; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.Scheduling.Events; + +/// +/// Handler for the domain event raised when the execution cycle of a scheduled job is started. +/// +public class ScheduledJobCycleStartedDomainEventHandler : IDomainEventHandler +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IScheduledJobNotifier _scheduledJobNotifier; + private readonly IScheduledJobScheduler _scheduledJobScheduler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for notifying the scheduled job changes to SignalR clients. + /// Injected service that schedules and executes the tasks of scheduled jobs. + /// Injected unit of work for interacting with the data access layer repositories. + public ScheduledJobCycleStartedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IScheduledJobScheduler scheduledJobScheduler, IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + _scheduledJobNotifier = scheduledJobNotifier; + _scheduledJobScheduler = scheduledJobScheduler; + } + + /// + /// Handles the event raised when the execution cycle of a scheduled job is started. + /// + /// The domain event to be handled. + /// Cancellation token that can be used to stop the execution. + public async ValueTask HandleAsync(ScheduledJobCycleStartedDomainEvent domainEvent, CancellationToken cancellationToken) + { + // Start the execution cycle in the scheduler service, which runs the task of the scheduled job once immediately and then on its schedule. + await _scheduledJobScheduler.StartCycleAsync(domainEvent.ScheduledJobId, cancellationToken).ConfigureAwait(false); + + Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + if (getScheduledJobsResult.IsFailure) + throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors); + IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())]; + await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobCycleStoppedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobCycleStoppedDomainEventHandler.cs new file mode 100644 index 00000000..a04da146 --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobCycleStoppedDomainEventHandler.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Application.Core.Scheduling.Notifications; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Exceptions; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.Scheduling.Events; + +/// +/// Handler for the domain event raised when the execution cycle of a scheduled job is stopped. +/// +public class ScheduledJobCycleStoppedDomainEventHandler : IDomainEventHandler +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IScheduledJobNotifier _scheduledJobNotifier; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for notifying the scheduled job changes to SignalR clients. + /// Injected unit of work for interacting with the data access layer repositories. + public ScheduledJobCycleStoppedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + _scheduledJobNotifier = scheduledJobNotifier; + } + + /// + /// Handles the event raised when the execution cycle of a scheduled job is stopped. + /// + /// The domain event to be handled. + /// Cancellation token that can be used to stop the execution. + public async ValueTask HandleAsync(ScheduledJobCycleStoppedDomainEvent domainEvent, CancellationToken cancellationToken) + { + Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + if (getScheduledJobsResult.IsFailure) + throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors); + IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())]; + await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandler.cs new file mode 100644 index 00000000..6d2df8ee --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandler.cs @@ -0,0 +1,148 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Application.Core.Scheduling.Notifications; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Exceptions; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.Scheduling.Events; + +/// +/// Handler for the domain event raised when the task of a scheduled job completes its execution. +/// +public class ScheduledJobExecutionCompletedDomainEventHandler : IDomainEventHandler +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IScheduledJobNotifier _scheduledJobNotifier; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for notifying the scheduled job changes to SignalR clients. + /// Injected unit of work for interacting with the data access layer repositories. + public ScheduledJobExecutionCompletedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + _scheduledJobNotifier = scheduledJobNotifier; + } + + /// + /// Handles the event raised when the task of a scheduled job completes its execution. + /// + /// The domain event to be handled. + /// Cancellation token that can be used to stop the execution. + public async ValueTask HandleAsync(ScheduledJobExecutionCompletedDomainEvent domainEvent, CancellationToken cancellationToken) + { + // Get the scheduled job from the repository. + Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken).ConfigureAwait(false); + if (getScheduledJobResult.IsFailure) + throw new EventualConsistencyException(getScheduledJobResult.FirstError, getScheduledJobResult.Errors); + if (getScheduledJobResult.Value is null) + throw new EventualConsistencyException(Errors.Scheduling.ScheduledJobNotFound); + ScheduledJobEntity scheduledJob = getScheduledJobResult.Value; + + // A cycle run returns the scheduled job to its active status, a one time execution completes it. + ScheduledJobStatus status = domainEvent.IsCycleRun ? ScheduledJobStatus.Active : ScheduledJobStatus.Completed; + ScheduledJobEntity updatedScheduledJob = CreateUpdatedScheduledJob(scheduledJob, status, scheduledJob.LastStartedOnUtc, domainEvent.CompletedOnUtc); + Result updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(updatedScheduledJob, cancellationToken).ConfigureAwait(false); + if (updateScheduledJobResult.IsFailure) + throw new EventualConsistencyException(updateScheduledJobResult.FirstError, updateScheduledJobResult.Errors); + + // Mark the execution of the task of the scheduled job as completed. + Result getExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, cancellationToken).ConfigureAwait(false); + if (getExecutionResult.IsFailure) + throw new EventualConsistencyException(getExecutionResult.FirstError, getExecutionResult.Errors); + if (getExecutionResult.Value is null) + throw new EventualConsistencyException(Errors.Scheduling.ScheduledJobExecutionNotFound); + ScheduledJobExecutionEntity execution = getExecutionResult.Value; + ScheduledJobExecutionEntity updatedExecution = CreateUpdatedExecution(execution, domainEvent.CompletedOnUtc); + Result updateExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.UpdateAsync(updatedExecution, cancellationToken).ConfigureAwait(false); + if (updateExecutionResult.IsFailure) + throw new EventualConsistencyException(updateExecutionResult.FirstError, updateExecutionResult.Errors); + + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + // Notify the SignalR clients about the current scheduled jobs and the completed execution. + await NotifyCurrentScheduledJobsAsync(cancellationToken).ConfigureAwait(false); + await _scheduledJobNotifier.SendScheduledJobExecutionCompletedAsync(updatedExecution.ToResponse(), cancellationToken).ConfigureAwait(false); + } + + /// + /// Creates a copy of with the provided status and timestamps. + /// + /// The scheduled job to copy. + /// The status of the copy. + /// The last start time of the copy. + /// The last completion time of the copy. + /// The copy of the scheduled job. + private static ScheduledJobEntity CreateUpdatedScheduledJob(ScheduledJobEntity scheduledJob, ScheduledJobStatus status, DateTime? lastStartedOnUtc, DateTime? lastCompletedOnUtc) + { + return new ScheduledJobEntity + { + Id = scheduledJob.Id, + Name = scheduledJob.Name, + TaskType = scheduledJob.TaskType, + ScheduleType = scheduledJob.ScheduleType, + IntervalMinutes = scheduledJob.IntervalMinutes, + Hour = scheduledJob.Hour, + Minute = scheduledJob.Minute, + Status = status, + OwnerUserId = scheduledJob.OwnerUserId, + LastStartedOnUtc = lastStartedOnUtc, + LastCompletedOnUtc = lastCompletedOnUtc, + CreatedOnUtc = scheduledJob.CreatedOnUtc, + CreatedBy = scheduledJob.CreatedBy, + UpdatedOnUtc = scheduledJob.UpdatedOnUtc, + UpdatedBy = scheduledJob.UpdatedBy + }; + } + + /// + /// Creates a copy of with the provided completion time. + /// + /// The execution to copy. + /// The completion time of the copy. + /// The copy of the execution. + private static ScheduledJobExecutionEntity CreateUpdatedExecution(ScheduledJobExecutionEntity execution, DateTime? completedOnUtc) + { + return new ScheduledJobExecutionEntity + { + Id = execution.Id, + ScheduledJobId = execution.ScheduledJobId, + TaskType = execution.TaskType, + IsCycleRun = execution.IsCycleRun, + WasCycleActive = execution.WasCycleActive, + StartedOnUtc = execution.StartedOnUtc, + CompletedOnUtc = completedOnUtc, + CreatedOnUtc = execution.CreatedOnUtc, + CreatedBy = execution.CreatedBy, + UpdatedOnUtc = execution.UpdatedOnUtc, + UpdatedBy = execution.UpdatedBy + }; + } + + /// + /// Notifies the SignalR clients about the current list of scheduled jobs. + /// + /// Cancellation token that can be used to stop the execution. + private async Task NotifyCurrentScheduledJobsAsync(CancellationToken cancellationToken) + { + Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + if (getScheduledJobsResult.IsFailure) + throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors); + IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())]; + await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandler.cs new file mode 100644 index 00000000..2e81591f --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandler.cs @@ -0,0 +1,133 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Application.Core.Scheduling.Notifications; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Exceptions; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.Scheduling.Events; + +/// +/// Handler for the domain event raised when the task of a scheduled job starts its execution. +/// +public class ScheduledJobExecutionStartedDomainEventHandler : IDomainEventHandler +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IScheduledJobNotifier _scheduledJobNotifier; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for notifying the scheduled job changes to SignalR clients. + /// Injected unit of work for interacting with the data access layer repositories. + public ScheduledJobExecutionStartedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + _scheduledJobNotifier = scheduledJobNotifier; + } + + /// + /// Handles the event raised when the task of a scheduled job starts its execution. + /// + /// The domain event to be handled. + /// Cancellation token that can be used to stop the execution. + public async ValueTask HandleAsync(ScheduledJobExecutionStartedDomainEvent domainEvent, CancellationToken cancellationToken) + { + // Get the scheduled job from the repository. + Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken).ConfigureAwait(false); + if (getScheduledJobResult.IsFailure) + throw new EventualConsistencyException(getScheduledJobResult.FirstError, getScheduledJobResult.Errors); + if (getScheduledJobResult.Value is null) + throw new EventualConsistencyException(Errors.Scheduling.ScheduledJobNotFound); + ScheduledJobEntity scheduledJob = getScheduledJobResult.Value; + // The execution cycle is active when the scheduled job was in its active state before this execution started; the + // status is read before the scheduled job is updated to its running state below. + bool wasCycleActive = scheduledJob.Status == ScheduledJobStatus.Active; + + // Update the scheduled job with its running status and the start time of the execution. + ScheduledJobEntity updatedScheduledJob = CreateUpdatedScheduledJob(scheduledJob, ScheduledJobStatus.Running, domainEvent.StartedOnUtc, scheduledJob.LastCompletedOnUtc); + Result updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(updatedScheduledJob, cancellationToken).ConfigureAwait(false); + if (updateScheduledJobResult.IsFailure) + throw new EventualConsistencyException(updateScheduledJobResult.FirstError, updateScheduledJobResult.Errors); + + // Insert the execution of the task of the scheduled job into the repository. + ScheduledJobExecutionEntity execution = new() + { + Id = domainEvent.RunId, + ScheduledJobId = scheduledJob.Id, + TaskType = scheduledJob.TaskType, + IsCycleRun = domainEvent.IsCycleRun, + WasCycleActive = wasCycleActive, + StartedOnUtc = domainEvent.StartedOnUtc, + CompletedOnUtc = null, + CreatedOnUtc = scheduledJob.CreatedOnUtc, + CreatedBy = scheduledJob.CreatedBy, + UpdatedOnUtc = null, + UpdatedBy = null + }; + Result insertExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.InsertAsync(execution, cancellationToken).ConfigureAwait(false); + if (insertExecutionResult.IsFailure) + throw new EventualConsistencyException(insertExecutionResult.FirstError, insertExecutionResult.Errors); + + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + // Notify the SignalR clients about the current scheduled jobs and the started execution. + await NotifyCurrentScheduledJobsAsync(cancellationToken).ConfigureAwait(false); + await _scheduledJobNotifier.SendScheduledJobExecutionStartedAsync(execution.ToResponse(), cancellationToken).ConfigureAwait(false); + } + + /// + /// Creates a copy of with the provided status and timestamps. + /// + /// The scheduled job to copy. + /// The status of the copy. + /// The last start time of the copy. + /// The last completion time of the copy. + /// The copy of the scheduled job. + private static ScheduledJobEntity CreateUpdatedScheduledJob(ScheduledJobEntity scheduledJob, ScheduledJobStatus status, DateTime? lastStartedOnUtc, DateTime? lastCompletedOnUtc) + { + return new ScheduledJobEntity + { + Id = scheduledJob.Id, + Name = scheduledJob.Name, + TaskType = scheduledJob.TaskType, + ScheduleType = scheduledJob.ScheduleType, + IntervalMinutes = scheduledJob.IntervalMinutes, + Hour = scheduledJob.Hour, + Minute = scheduledJob.Minute, + Status = status, + OwnerUserId = scheduledJob.OwnerUserId, + LastStartedOnUtc = lastStartedOnUtc, + LastCompletedOnUtc = lastCompletedOnUtc, + CreatedOnUtc = scheduledJob.CreatedOnUtc, + CreatedBy = scheduledJob.CreatedBy, + UpdatedOnUtc = scheduledJob.UpdatedOnUtc, + UpdatedBy = scheduledJob.UpdatedBy + }; + } + + /// + /// Notifies the SignalR clients about the current list of scheduled jobs. + /// + /// Cancellation token that can be used to stop the execution. + private async Task NotifyCurrentScheduledJobsAsync(CancellationToken cancellationToken) + { + Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + if (getScheduledJobsResult.IsFailure) + throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors); + IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())]; + await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandler.cs new file mode 100644 index 00000000..cc735453 --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandler.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Application.Core.Scheduling.Notifications; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Exceptions; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.Scheduling.Events; + +/// +/// Handler for the domain event raised when the execution of the task of a scheduled job is stopped while it is running. +/// +public class ScheduledJobExecutionStoppedDomainEventHandler : IDomainEventHandler +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IScheduledJobNotifier _scheduledJobNotifier; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for notifying the scheduled job changes to SignalR clients. + /// Injected unit of work for interacting with the data access layer repositories. + public ScheduledJobExecutionStoppedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + _scheduledJobNotifier = scheduledJobNotifier; + } + + /// + /// Handles the event raised when the execution of the task of a scheduled job is stopped while it is running. + /// + /// The domain event to be handled. + /// Cancellation token that can be used to stop the execution. + public async ValueTask HandleAsync(ScheduledJobExecutionStoppedDomainEvent domainEvent, CancellationToken cancellationToken) + { + // Close the execution history row of the stopped execution, if it exists. + Result getOpenExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository + .GetOpenByScheduledJobIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken).ConfigureAwait(false); + if (getOpenExecutionResult.IsFailure) + throw new EventualConsistencyException(getOpenExecutionResult.FirstError, getOpenExecutionResult.Errors); + if (getOpenExecutionResult.Value is not null) + { + ScheduledJobExecutionEntity execution = getOpenExecutionResult.Value; + ScheduledJobExecutionEntity updatedExecution = new() + { + Id = execution.Id, + ScheduledJobId = execution.ScheduledJobId, + TaskType = execution.TaskType, + IsCycleRun = execution.IsCycleRun, + WasCycleActive = execution.WasCycleActive, + StartedOnUtc = execution.StartedOnUtc, + CompletedOnUtc = domainEvent.OccurredOnUtc, + CreatedOnUtc = execution.CreatedOnUtc, + CreatedBy = execution.CreatedBy, + UpdatedOnUtc = execution.UpdatedOnUtc, + UpdatedBy = execution.UpdatedBy + }; + Result updateExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.UpdateAsync(updatedExecution, cancellationToken).ConfigureAwait(false); + if (updateExecutionResult.IsFailure) + throw new EventualConsistencyException(updateExecutionResult.FirstError, updateExecutionResult.Errors); + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + // Notify the SignalR clients about the current list of scheduled jobs. + Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + if (getScheduledJobsResult.IsFailure) + throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors); + IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())]; + await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobFiredDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobFiredDomainEventHandler.cs new file mode 100644 index 00000000..aa29481e --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobFiredDomainEventHandler.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Scheduling; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.Scheduling.Events; + +/// +/// Handler for the domain event raised when the task of a scheduled job is fired once. +/// +public class ScheduledJobFiredDomainEventHandler : IDomainEventHandler +{ + private readonly IScheduledJobScheduler _scheduledJobScheduler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service that schedules and executes the tasks of scheduled jobs. + public ScheduledJobFiredDomainEventHandler(IScheduledJobScheduler scheduledJobScheduler) + { + _scheduledJobScheduler = scheduledJobScheduler; + } + + /// + /// Handles the event raised when the task of a scheduled job is fired once. + /// + /// The domain event to be handled. + /// Cancellation token that can be used to stop the execution. + public async ValueTask HandleAsync(ScheduledJobFiredDomainEvent domainEvent, CancellationToken cancellationToken) + { + // Start a one time execution of the task of the scheduled job in the scheduler service. + await _scheduledJobScheduler.RunOnceAsync(domainEvent.ScheduledJobId, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobRemovedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobRemovedDomainEventHandler.cs new file mode 100644 index 00000000..892a64f4 --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobRemovedDomainEventHandler.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Application.Core.Scheduling.Notifications; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Exceptions; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.Scheduling.Events; + +/// +/// Handler for the domain event raised when a scheduled job is removed. +/// +public class ScheduledJobRemovedDomainEventHandler : IDomainEventHandler +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IScheduledJobNotifier _scheduledJobNotifier; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for notifying the scheduled job changes to SignalR clients. + /// Injected unit of work for interacting with the data access layer repositories. + public ScheduledJobRemovedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + _scheduledJobNotifier = scheduledJobNotifier; + } + + /// + /// Handles the event raised when a scheduled job is removed. + /// + /// The domain event to be handled. + /// Cancellation token that can be used to stop the execution. + public async ValueTask HandleAsync(ScheduledJobRemovedDomainEvent domainEvent, CancellationToken cancellationToken) + { + Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + if (getScheduledJobsResult.IsFailure) + throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors); + IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())]; + await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Application/Core/Scheduling/Notifications/IScheduledJobNotifier.cs b/src/Lumina.Application/Core/Scheduling/Notifications/IScheduledJobNotifier.cs new file mode 100644 index 00000000..4251a142 --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Notifications/IScheduledJobNotifier.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.Scheduling; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.Scheduling.Notifications; + +/// +/// Interface for the class used to notify SignalR clients about the scheduled jobs and their executions. +/// +public interface IScheduledJobNotifier +{ + /// + /// Notifies the SignalR clients about the current list of scheduled jobs. + /// + /// The current list of scheduled jobs. + /// Cancellation token that can be used to stop the execution. + Task SendScheduledJobsAsync(IReadOnlyList scheduledJobs, CancellationToken cancellationToken); + + /// + /// Notifies the SignalR clients about an execution of the task of a scheduled job that started. + /// + /// The execution of the task of the scheduled job that started. + /// Cancellation token that can be used to stop the execution. + Task SendScheduledJobExecutionStartedAsync(ScheduledJobExecutionResponse execution, CancellationToken cancellationToken); + + /// + /// Notifies the SignalR clients about an execution of the task of a scheduled job that completed. + /// + /// The execution of the task of the scheduled job that completed. + /// Cancellation token that can be used to stop the execution. + Task SendScheduledJobExecutionCompletedAsync(ScheduledJobExecutionResponse execution, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQuery.cs b/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQuery.cs new file mode 100644 index 00000000..edac9854 --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQuery.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Scheduling.Queries.GetScheduledJobHistory; + +/// +/// Query for getting the history of the executions of the tasks of scheduled jobs. +/// +/// The optional inclusive lower bound of the interval for which the history is requested. +/// The optional inclusive upper bound of the interval for which the history is requested. +[DebuggerDisplay("From: {From}, To: {To}")] +public record GetScheduledJobHistoryQuery( + DateTime? From, + DateTime? To +) : IQuery; diff --git a/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQueryHandler.cs b/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQueryHandler.cs new file mode 100644 index 00000000..bb9378e9 --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQueryHandler.cs @@ -0,0 +1,76 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Scheduling.Queries.GetScheduledJobHistory; + +/// +/// Handler for the query to get the history of the executions of the tasks of scheduled jobs. +/// +public class GetScheduledJobHistoryQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected unit of work for interacting with the data access layer repositories. + public GetScheduledJobHistoryQueryHandler( + IAuthorizationService authorizationService, + ICurrentUserService currentUserService, + IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + } + + /// + /// Handles the query to get the history of the executions of the tasks of scheduled jobs. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the execution history, or an error. + /// + public async Task>> HandleAsync(GetScheduledJobHistoryQuery query, CancellationToken cancellationToken) + { + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // Only administrators can get the history of scheduled jobs. + if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false)) + return ApplicationErrors.Authorization.NotAuthorized; + + // The lower bound defaults to one day before the upper bound, which defaults to now. + DateTime toUtc = query.To ?? DateTime.UtcNow; + DateTime fromUtc = query.From ?? toUtc.AddDays(-1); + + // Get the executions from the storage medium. + Result> getExecutionsResult = await _unitOfWork.ScheduledJobExecutionRepository.GetByTimeRangeAsync(fromUtc, toUtc, cancellationToken).ConfigureAwait(false); + if (getExecutionsResult.IsFailure) + return getExecutionsResult.Errors; + + return Result.From(getExecutionsResult.Value.Select(execution => execution.ToResponse())); + } +} diff --git a/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQuery.cs b/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQuery.cs new file mode 100644 index 00000000..99ca2129 --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQuery.cs @@ -0,0 +1,12 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Scheduling.Queries.GetScheduledJobs; + +/// +/// Query for getting the list of scheduled jobs. +/// +[DebuggerDisplay("GetScheduledJobsQuery")] +public record GetScheduledJobsQuery : IQuery; diff --git a/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQueryHandler.cs b/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQueryHandler.cs new file mode 100644 index 00000000..9991ac07 --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQueryHandler.cs @@ -0,0 +1,72 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Scheduling.Queries.GetScheduledJobs; + +/// +/// Handler for the query to get the list of scheduled jobs. +/// +public class GetScheduledJobsQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected unit of work for interacting with the data access layer repositories. + public GetScheduledJobsQueryHandler( + IAuthorizationService authorizationService, + ICurrentUserService currentUserService, + IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + } + + /// + /// Handles the query to get the list of scheduled jobs. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the list of scheduled jobs, or an error. + /// + public async Task>> HandleAsync(GetScheduledJobsQuery query, CancellationToken cancellationToken) + { + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // Only administrators can get the list of scheduled jobs. + if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false)) + return ApplicationErrors.Authorization.NotAuthorized; + + // Get the scheduled jobs from the storage medium. + Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + if (getScheduledJobsResult.IsFailure) + return getScheduledJobsResult.Errors; + + return Result.From(getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())); + } +} diff --git a/src/Lumina.Application/Core/Scheduling/Queries/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesQuery.cs b/src/Lumina.Application/Core/Scheduling/Queries/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesQuery.cs new file mode 100644 index 00000000..6f12960a --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Queries/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesQuery.cs @@ -0,0 +1,10 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +#endregion + +namespace Lumina.Application.Core.Scheduling.Queries.GetSchedulerDisplayPreferences; + +/// +/// Query for getting the display preferences of the scheduler page of the current user. +/// +public record GetSchedulerDisplayPreferencesQuery : IQuery; diff --git a/src/Lumina.Application/Core/Scheduling/Queries/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesQueryHandler.cs b/src/Lumina.Application/Core/Scheduling/Queries/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesQueryHandler.cs new file mode 100644 index 00000000..eeaaff89 --- /dev/null +++ b/src/Lumina.Application/Core/Scheduling/Queries/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesQueryHandler.cs @@ -0,0 +1,72 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Primitives; +using System; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Scheduling.Queries.GetSchedulerDisplayPreferences; + +/// +/// Handler for the query to get the display preferences of the scheduler page of the current user. +/// +public class GetSchedulerDisplayPreferencesQueryHandler : IQueryHandler> +{ + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IUnitOfWork _unitOfWork; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected unit of work for interacting with the data access layer repositories. + public GetSchedulerDisplayPreferencesQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork) + { + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _unitOfWork = unitOfWork; + } + + /// + /// Handles the query to get the display preferences of the scheduler page of the current user. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the display preferences of the scheduler page of the current user, or an error. + /// + public async Task> HandleAsync(GetSchedulerDisplayPreferencesQuery query, CancellationToken cancellationToken) + { + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // Only administrators can view the scheduler page. + if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false)) + return ApplicationErrors.Authorization.NotAuthorized; + + // Get the display preferences of the scheduler page of the current user from the repository. + Result getDisplayPreferencesResult = await _unitOfWork.SchedulerDisplayPreferencesRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false); + if (getDisplayPreferencesResult.IsFailure) + return getDisplayPreferencesResult.Errors; + + // When no display preferences are stored for the current user yet, return the default display preferences. + if (getDisplayPreferencesResult.Value is null) + return getDisplayPreferencesResult.Value.ToDefaultResponse(userId); + + return getDisplayPreferencesResult.Value.ToResponse(); + } +} diff --git a/src/Lumina.Contracts/Requests/Scheduling/AddScheduledJobRequest.cs b/src/Lumina.Contracts/Requests/Scheduling/AddScheduledJobRequest.cs new file mode 100644 index 00000000..e80fafb5 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Scheduling/AddScheduledJobRequest.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Scheduling; + +/// +/// Represents a request to add a scheduled job. +/// +/// The name of the scheduled job. Required. +/// The type of the task executed by the scheduled job. Required. +/// The type of the schedule of the scheduled job. Required. +/// The interval in minutes of the schedule, required when is . +/// The hour of the schedule, required when is . +/// The minute of the schedule, required when is . +[DebuggerDisplay("Name: {Name}")] +public record AddScheduledJobRequest( + string Name, + ScheduledTaskType TaskType, + ScheduleType ScheduleType, + int? IntervalMinutes, + int? Hour, + int? Minute +); diff --git a/src/Lumina.Contracts/Requests/Scheduling/FireScheduledJobRequest.cs b/src/Lumina.Contracts/Requests/Scheduling/FireScheduledJobRequest.cs new file mode 100644 index 00000000..53187070 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Scheduling/FireScheduledJobRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Scheduling; + +/// +/// Represents a request to fire the task of a scheduled job once, without affecting its execution cycle. +/// +/// The unique identifier of the scheduled job whose task is fired. Required. +[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")] +public record FireScheduledJobRequest( + Guid ScheduledJobId +); diff --git a/src/Lumina.Contracts/Requests/Scheduling/GetScheduledJobHistoryRequest.cs b/src/Lumina.Contracts/Requests/Scheduling/GetScheduledJobHistoryRequest.cs new file mode 100644 index 00000000..e95b9f94 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Scheduling/GetScheduledJobHistoryRequest.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Scheduling; + +/// +/// Represents a request to get the history of the executions of the tasks of scheduled jobs. +/// +/// The inclusive lower bound of the interval for which the history is requested. Optional. +/// The inclusive upper bound of the interval for which the history is requested. Optional. +[DebuggerDisplay("From: {From}, To: {To}")] +public record GetScheduledJobHistoryRequest( + DateTime? From, + DateTime? To +); diff --git a/src/Lumina.Contracts/Requests/Scheduling/RemoveScheduledJobRequest.cs b/src/Lumina.Contracts/Requests/Scheduling/RemoveScheduledJobRequest.cs new file mode 100644 index 00000000..5b3dd987 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Scheduling/RemoveScheduledJobRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Scheduling; + +/// +/// Represents a request to remove a scheduled job. +/// +/// The unique identifier of the scheduled job to remove. Required. +[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")] +public record RemoveScheduledJobRequest( + Guid ScheduledJobId +); diff --git a/src/Lumina.Contracts/Requests/Scheduling/StartScheduledJobRequest.cs b/src/Lumina.Contracts/Requests/Scheduling/StartScheduledJobRequest.cs new file mode 100644 index 00000000..63448b47 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Scheduling/StartScheduledJobRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Scheduling; + +/// +/// Represents a request to start the execution cycle of a scheduled job. +/// +/// The unique identifier of the scheduled job whose execution cycle is started. Required. +[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")] +public record StartScheduledJobRequest( + Guid ScheduledJobId +); diff --git a/src/Lumina.Contracts/Requests/Scheduling/StopScheduledJobRequest.cs b/src/Lumina.Contracts/Requests/Scheduling/StopScheduledJobRequest.cs new file mode 100644 index 00000000..36c3f0af --- /dev/null +++ b/src/Lumina.Contracts/Requests/Scheduling/StopScheduledJobRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Scheduling; + +/// +/// Represents a request to stop the execution cycle of a scheduled job. +/// +/// The unique identifier of the scheduled job whose execution cycle is stopped. Required. +[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")] +public record StopScheduledJobRequest( + Guid ScheduledJobId +); diff --git a/src/Lumina.Contracts/Requests/Scheduling/UpdateSchedulerDisplayPreferencesRequest.cs b/src/Lumina.Contracts/Requests/Scheduling/UpdateSchedulerDisplayPreferencesRequest.cs new file mode 100644 index 00000000..ff546221 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Scheduling/UpdateSchedulerDisplayPreferencesRequest.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Scheduling; + +/// +/// Represents a request to update the display preferences of the scheduler page of the current user. +/// +/// The type of the scheduled job tasks whose executions are shown on the scheduler page, or when all of them are shown. +/// The time span, expressed in , that the scheduler page shows. Required. +/// The unit in which the displayed time span of the scheduler page is expressed. Required. +[DebuggerDisplay("DisplayTimeSpan: {DisplayTimeSpan} {DisplayTimeUnit}")] +public sealed record UpdateSchedulerDisplayPreferencesRequest( + ScheduledTaskType? JobTypeFilter, + int DisplayTimeSpan, + SchedulerDisplayTimeUnit DisplayTimeUnit +); diff --git a/src/Lumina.Contracts/Responses/Scheduling/ScheduledJobExecutionResponse.cs b/src/Lumina.Contracts/Responses/Scheduling/ScheduledJobExecutionResponse.cs new file mode 100644 index 00000000..4f33a189 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Scheduling/ScheduledJobExecutionResponse.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Scheduling; + +/// +/// Represents an execution of the task of a scheduled job. +/// +/// The unique identifier of the execution. +/// The unique identifier of the scheduled job whose task was executed. +/// The type of the task that was executed. +/// when the execution was triggered by the execution cycle of the scheduled job, when it was a one time execution. +/// The date and time when the execution started. +/// The optional date and time when the execution completed. +[DebuggerDisplay("Id: {Id}, ScheduledJobId: {ScheduledJobId}")] +public record ScheduledJobExecutionResponse( + Guid Id, + Guid ScheduledJobId, + ScheduledTaskType TaskType, + bool IsCycleRun, + DateTime StartedOnUtc, + DateTime? CompletedOnUtc +); diff --git a/src/Lumina.Contracts/Responses/Scheduling/ScheduledJobResponse.cs b/src/Lumina.Contracts/Responses/Scheduling/ScheduledJobResponse.cs new file mode 100644 index 00000000..c1c53a2b --- /dev/null +++ b/src/Lumina.Contracts/Responses/Scheduling/ScheduledJobResponse.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Scheduling; + +/// +/// Represents a scheduled job response. +/// +/// The unique identifier of the scheduled job. +/// The name of the scheduled job. +/// The type of the task executed by the scheduled job. +/// The type of the schedule of the scheduled job. +/// The interval in minutes of the schedule of the scheduled job, when its is . +/// The hour of the schedule of the scheduled job, when its is . +/// The minute of the schedule of the scheduled job, when its is . +/// The status of the scheduled job. +/// The optional date and time when the task of the scheduled job last started its execution. +/// The optional date and time when the task of the scheduled job last completed its execution. +[DebuggerDisplay("Id: {Id}, Name: {Name}, Status: {Status}")] +public record ScheduledJobResponse( + Guid Id, + string Name, + ScheduledTaskType TaskType, + ScheduleType ScheduleType, + int? IntervalMinutes, + int? Hour, + int? Minute, + ScheduledJobStatus Status, + DateTime? LastStartedOnUtc, + DateTime? LastCompletedOnUtc +); diff --git a/src/Lumina.Contracts/Responses/Scheduling/SchedulerDisplayPreferencesResponse.cs b/src/Lumina.Contracts/Responses/Scheduling/SchedulerDisplayPreferencesResponse.cs new file mode 100644 index 00000000..d762eccf --- /dev/null +++ b/src/Lumina.Contracts/Responses/Scheduling/SchedulerDisplayPreferencesResponse.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Scheduling; + +/// +/// Represents the display preferences of the scheduler page of a user. +/// +/// The unique identifier of the user that owns the display preferences. +/// The type of the scheduled job tasks whose executions are shown on the scheduler page, or when all of them are shown. +/// The time span, expressed in , that the scheduler page shows. +/// The unit in which the displayed time span of the scheduler page is expressed. +[DebuggerDisplay("UserId: {UserId}, DisplayTimeSpan: {DisplayTimeSpan} {DisplayTimeUnit}")] +public sealed record SchedulerDisplayPreferencesResponse( + Guid UserId, + ScheduledTaskType? JobTypeFilter, + int DisplayTimeSpan, + SchedulerDisplayTimeUnit DisplayTimeUnit +); diff --git a/src/Lumina.DataAccess/Common/Configuration/ScheduledJobConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/ScheduledJobConfiguration.cs new file mode 100644 index 00000000..84b984f5 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/ScheduledJobConfiguration.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using System; +#endregion + +namespace Lumina.DataAccess.Common.Configuration; + +/// +/// Configures the entity mapping for the entity. +/// +public class ScheduledJobConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("ScheduledJobs"); + builder.HasKey(scheduledJob => scheduledJob.Id); + builder.Property(scheduledJob => scheduledJob.Id) + .ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it + .HasColumnOrder(0); + + builder.Property(scheduledJob => scheduledJob.Name) + .IsRequired() + .HasColumnOrder(1); + + builder.Property(scheduledJob => scheduledJob.TaskType) + .IsRequired() + .HasConversion() + .HasColumnOrder(2); + + builder.Property(scheduledJob => scheduledJob.ScheduleType) + .IsRequired() + .HasConversion() + .HasColumnOrder(3); + + builder.Property(scheduledJob => scheduledJob.IntervalMinutes) + .HasColumnOrder(4); + + builder.Property(scheduledJob => scheduledJob.Hour) + .HasColumnOrder(5); + + builder.Property(scheduledJob => scheduledJob.Minute) + .HasColumnOrder(6); + + builder.Property(scheduledJob => scheduledJob.Status) + .IsRequired() + .HasConversion() + .HasColumnOrder(7); + + builder.Property(scheduledJob => scheduledJob.OwnerUserId) + .IsRequired() + .HasColumnOrder(8); + + builder.Property(scheduledJob => scheduledJob.LastStartedOnUtc) + .HasColumnOrder(9); + + builder.Property(scheduledJob => scheduledJob.LastCompletedOnUtc) + .HasColumnOrder(10); + + // Audit. + builder.Property(scheduledJob => scheduledJob.CreatedOnUtc) + .IsRequired() + .HasColumnOrder(11); + + builder.Property(scheduledJob => scheduledJob.CreatedBy) + .IsRequired() + .HasColumnOrder(12); + + builder.Property(scheduledJob => scheduledJob.UpdatedOnUtc) + .HasDefaultValue(null) + .HasColumnOrder(13); + + builder.Property(scheduledJob => scheduledJob.UpdatedBy) + .HasDefaultValue(null) + .HasColumnOrder(14); + + // Enables fast lookup of the scheduled jobs whose execution cycle is active, at scheduler startup. + builder.HasIndex(scheduledJob => scheduledJob.Status); + } +} diff --git a/src/Lumina.DataAccess/Common/Configuration/ScheduledJobExecutionConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/ScheduledJobExecutionConfiguration.cs new file mode 100644 index 00000000..64053b4a --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/ScheduledJobExecutionConfiguration.cs @@ -0,0 +1,72 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using System; +#endregion + +namespace Lumina.DataAccess.Common.Configuration; + +/// +/// Configures the entity mapping for the entity. +/// +public class ScheduledJobExecutionConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("ScheduledJobExecutions"); + builder.HasKey(execution => execution.Id); + builder.Property(execution => execution.Id) + .ValueGeneratedNever() + .HasColumnOrder(0); + + builder.Property(execution => execution.ScheduledJobId) + .IsRequired() + .HasColumnOrder(1); + + builder.Property(execution => execution.TaskType) + .IsRequired() + .HasConversion() + .HasColumnOrder(2); + + builder.Property(execution => execution.IsCycleRun) + .IsRequired() + .HasColumnOrder(3); + + builder.Property(execution => execution.StartedOnUtc) + .IsRequired() + .HasColumnOrder(4); + + builder.Property(execution => execution.CompletedOnUtc) + .HasColumnOrder(5); + + builder.Property(execution => execution.WasCycleActive) + .IsRequired() + .HasColumnOrder(6); + + // Audit. + builder.Property(execution => execution.CreatedOnUtc) + .IsRequired() + .HasColumnOrder(7); + + builder.Property(execution => execution.CreatedBy) + .IsRequired() + .HasColumnOrder(8); + + builder.Property(execution => execution.UpdatedOnUtc) + .HasDefaultValue(null) + .HasColumnOrder(9); + + builder.Property(execution => execution.UpdatedBy) + .HasDefaultValue(null) + .HasColumnOrder(10); + + // Enables fast queries of the execution history of scheduled jobs by their time range, and the cleanup of the executions of a removed scheduled job. + builder.HasIndex(execution => new { execution.StartedOnUtc, execution.ScheduledJobId }); + builder.HasIndex(execution => execution.ScheduledJobId); + } +} diff --git a/src/Lumina.DataAccess/Common/Configuration/SchedulerDisplayPreferencesConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/SchedulerDisplayPreferencesConfiguration.cs new file mode 100644 index 00000000..698aaac7 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/SchedulerDisplayPreferencesConfiguration.cs @@ -0,0 +1,65 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using System; +#endregion + +namespace Lumina.DataAccess.Common.Configuration; + +/// +/// Configures the entity mapping for the entity. +/// +public class SchedulerDisplayPreferencesConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("SchedulerDisplayPreferences"); + builder.HasKey(preferences => preferences.Id); + builder.Property(preferences => preferences.Id) + .ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it + .HasColumnOrder(0); + + builder.Property(preferences => preferences.UserId) + .IsRequired() + .HasColumnOrder(1); + + builder.Property(preferences => preferences.JobTypeFilter) + .HasConversion() + .HasColumnOrder(2); + + builder.Property(preferences => preferences.DisplayTimeSpan) + .IsRequired() + .HasColumnOrder(3); + + builder.Property(preferences => preferences.DisplayTimeUnit) + .IsRequired() + .HasConversion() + .HasColumnOrder(4); + + // Audit. + builder.Property(preferences => preferences.CreatedOnUtc) + .IsRequired() + .HasColumnOrder(5); + + builder.Property(preferences => preferences.CreatedBy) + .IsRequired() + .HasColumnOrder(6); + + builder.Property(preferences => preferences.UpdatedOnUtc) + .HasDefaultValue(null) + .HasColumnOrder(7); + + builder.Property(preferences => preferences.UpdatedBy) + .HasDefaultValue(null) + .HasColumnOrder(8); + + // One user has at most one set of scheduler page display preferences. + builder.HasIndex(preferences => preferences.UserId) + .IsUnique(); + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260903054819_AddsScheduledJobsTables.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20260903054819_AddsScheduledJobsTables.Designer.cs new file mode 100644 index 00000000..699b7ca3 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260903054819_AddsScheduledJobsTables.Designer.cs @@ -0,0 +1,1741 @@ +// . +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20260903054819_AddsScheduledJobsTables")] + partial class AddsScheduledJobsTables + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.BookContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("RoleCategory") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("BookId", "MediaContributorId"); + + b.ToTable("BookContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.MediaContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Biography") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DateOfBirth") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("DateOfDeath") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1) + .UseCollation("NOCASE"); + + b.Property("LegalName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.HasKey("Id"); + + b.HasIndex("DisplayName") + .IsUnique(); + + b.ToTable("MediaContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("BookId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("BookArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("REAL") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path"); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryArtworkProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryBookReaderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); + + b.ToTable("LibraryBookReaderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Hour") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("IntervalMinutes") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("LastCompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastStartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Minute") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("OwnerUserId") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ScheduleType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.ToTable("ScheduledJobs", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobExecutionEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("IsCycleRun") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ScheduledJobId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.HasKey("Id"); + + b.HasIndex("ScheduledJobId"); + + b.HasIndex("StartedOnUtc", "ScheduledJobId"); + + b.ToTable("ScheduledJobExecutions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Version") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.HasIndex("IsCurrent") + .IsUnique() + .HasFilter("IsCurrent = 1"); + + b.HasIndex("ThemeId") + .IsUnique(); + + b.ToTable("Themes", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("ShouldPreserveBookStyles") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("ShouldRenderPdfAsImages") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.BookContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("BookContributors") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("BookArtwork") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Navigation("BookArtwork"); + + b.Navigation("BookContributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260903054819_AddsScheduledJobsTables.cs b/src/Lumina.DataAccess/Common/Migrations/20260903054819_AddsScheduledJobsTables.cs new file mode 100644 index 00000000..70149d3a --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260903054819_AddsScheduledJobsTables.cs @@ -0,0 +1,85 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsScheduledJobsTables : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "ScheduledJobExecutions", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + ScheduledJobId = table.Column(type: "TEXT", nullable: false), + TaskType = table.Column(type: "TEXT", nullable: false), + IsCycleRun = table.Column(type: "INTEGER", nullable: false), + StartedOnUtc = table.Column(type: "TEXT", nullable: false), + CompletedOnUtc = table.Column(type: "TEXT", nullable: true), + CreatedOnUtc = table.Column(type: "TEXT", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: false), + UpdatedOnUtc = table.Column(type: "TEXT", nullable: true), + UpdatedBy = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ScheduledJobExecutions", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "ScheduledJobs", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Name = table.Column(type: "TEXT", nullable: false), + TaskType = table.Column(type: "TEXT", nullable: false), + ScheduleType = table.Column(type: "TEXT", nullable: false), + IntervalMinutes = table.Column(type: "INTEGER", nullable: true), + Hour = table.Column(type: "INTEGER", nullable: true), + Minute = table.Column(type: "INTEGER", nullable: true), + Status = table.Column(type: "TEXT", nullable: false), + OwnerUserId = table.Column(type: "TEXT", nullable: false), + LastStartedOnUtc = table.Column(type: "TEXT", nullable: true), + LastCompletedOnUtc = table.Column(type: "TEXT", nullable: true), + CreatedOnUtc = table.Column(type: "TEXT", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: false), + UpdatedOnUtc = table.Column(type: "TEXT", nullable: true), + UpdatedBy = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ScheduledJobs", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_ScheduledJobExecutions_ScheduledJobId", + table: "ScheduledJobExecutions", + column: "ScheduledJobId"); + + migrationBuilder.CreateIndex( + name: "IX_ScheduledJobExecutions_StartedOnUtc_ScheduledJobId", + table: "ScheduledJobExecutions", + columns: new[] { "StartedOnUtc", "ScheduledJobId" }); + + migrationBuilder.CreateIndex( + name: "IX_ScheduledJobs_Status", + table: "ScheduledJobs", + column: "Status"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ScheduledJobExecutions"); + + migrationBuilder.DropTable( + name: "ScheduledJobs"); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260903201036_AddsSchedulerDisplayPreferences.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20260903201036_AddsSchedulerDisplayPreferences.Designer.cs new file mode 100644 index 00000000..e11987b7 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260903201036_AddsSchedulerDisplayPreferences.Designer.cs @@ -0,0 +1,1788 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20260903201036_AddsSchedulerDisplayPreferences")] + partial class AddsSchedulerDisplayPreferences + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.BookContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("RoleCategory") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("BookId", "MediaContributorId"); + + b.ToTable("BookContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.MediaContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Biography") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DateOfBirth") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("DateOfDeath") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1) + .UseCollation("NOCASE"); + + b.Property("LegalName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.HasKey("Id"); + + b.HasIndex("DisplayName") + .IsUnique(); + + b.ToTable("MediaContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("BookId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("BookArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("REAL") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path"); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryArtworkProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryBookReaderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); + + b.ToTable("LibraryBookReaderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Hour") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("IntervalMinutes") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("LastCompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastStartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Minute") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("OwnerUserId") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ScheduleType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.ToTable("ScheduledJobs", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobExecutionEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("IsCycleRun") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ScheduledJobId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.HasKey("Id"); + + b.HasIndex("ScheduledJobId"); + + b.HasIndex("StartedOnUtc", "ScheduledJobId"); + + b.ToTable("ScheduledJobExecutions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.SchedulerDisplayPreferencesEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayTimeSpan") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("DisplayTimeUnit") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("JobTypeFilter") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("SchedulerDisplayPreferences", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Version") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.HasIndex("IsCurrent") + .IsUnique() + .HasFilter("IsCurrent = 1"); + + b.HasIndex("ThemeId") + .IsUnique(); + + b.ToTable("Themes", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("ShouldPreserveBookStyles") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("ShouldRenderPdfAsImages") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.BookContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("BookContributors") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("BookArtwork") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Navigation("BookArtwork"); + + b.Navigation("BookContributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260903201036_AddsSchedulerDisplayPreferences.cs b/src/Lumina.DataAccess/Common/Migrations/20260903201036_AddsSchedulerDisplayPreferences.cs new file mode 100644 index 00000000..80cac03b --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260903201036_AddsSchedulerDisplayPreferences.cs @@ -0,0 +1,47 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsSchedulerDisplayPreferences : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "SchedulerDisplayPreferences", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + UserId = table.Column(type: "TEXT", nullable: false), + JobTypeFilter = table.Column(type: "TEXT", nullable: true), + DisplayTimeSpan = table.Column(type: "INTEGER", nullable: false), + DisplayTimeUnit = table.Column(type: "TEXT", nullable: false), + CreatedOnUtc = table.Column(type: "TEXT", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: false), + UpdatedOnUtc = table.Column(type: "TEXT", nullable: true), + UpdatedBy = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_SchedulerDisplayPreferences", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_SchedulerDisplayPreferences_UserId", + table: "SchedulerDisplayPreferences", + column: "UserId", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "SchedulerDisplayPreferences"); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260904204717_AddsWasCycleActiveToScheduledJobExecutions.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20260904204717_AddsWasCycleActiveToScheduledJobExecutions.Designer.cs new file mode 100644 index 00000000..b457484e --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260904204717_AddsWasCycleActiveToScheduledJobExecutions.Designer.cs @@ -0,0 +1,1792 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20260904204717_AddsWasCycleActiveToScheduledJobExecutions")] + partial class AddsWasCycleActiveToScheduledJobExecutions + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.BookContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("RoleCategory") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("BookId", "MediaContributorId"); + + b.ToTable("BookContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.MediaContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Biography") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DateOfBirth") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("DateOfDeath") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1) + .UseCollation("NOCASE"); + + b.Property("LegalName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.HasKey("Id"); + + b.HasIndex("DisplayName") + .IsUnique(); + + b.ToTable("MediaContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("BookId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("BookArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("REAL") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path"); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryArtworkProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryBookReaderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); + + b.ToTable("LibraryBookReaderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Hour") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("IntervalMinutes") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("LastCompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastStartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Minute") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("OwnerUserId") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ScheduleType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.ToTable("ScheduledJobs", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobExecutionEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("IsCycleRun") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ScheduledJobId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("WasCycleActive") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("ScheduledJobId"); + + b.HasIndex("StartedOnUtc", "ScheduledJobId"); + + b.ToTable("ScheduledJobExecutions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.SchedulerDisplayPreferencesEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayTimeSpan") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("DisplayTimeUnit") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("JobTypeFilter") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("SchedulerDisplayPreferences", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Version") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.HasIndex("IsCurrent") + .IsUnique() + .HasFilter("IsCurrent = 1"); + + b.HasIndex("ThemeId") + .IsUnique(); + + b.ToTable("Themes", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("ShouldPreserveBookStyles") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("ShouldRenderPdfAsImages") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.BookContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("BookContributors") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("BookArtwork") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Navigation("BookArtwork"); + + b.Navigation("BookContributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260904204717_AddsWasCycleActiveToScheduledJobExecutions.cs b/src/Lumina.DataAccess/Common/Migrations/20260904204717_AddsWasCycleActiveToScheduledJobExecutions.cs new file mode 100644 index 00000000..d44ce67a --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260904204717_AddsWasCycleActiveToScheduledJobExecutions.cs @@ -0,0 +1,115 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsWasCycleActiveToScheduledJobExecutions : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "UpdatedOnUtc", + table: "ScheduledJobExecutions", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateTime), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 9) + .OldAnnotation("Relational:ColumnOrder", 8); + + migrationBuilder.AlterColumn( + name: "UpdatedBy", + table: "ScheduledJobExecutions", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 10) + .OldAnnotation("Relational:ColumnOrder", 9); + + migrationBuilder.AlterColumn( + name: "CreatedOnUtc", + table: "ScheduledJobExecutions", + type: "TEXT", + nullable: false, + oldClrType: typeof(DateTime), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 7) + .OldAnnotation("Relational:ColumnOrder", 6); + + migrationBuilder.AlterColumn( + name: "CreatedBy", + table: "ScheduledJobExecutions", + type: "TEXT", + nullable: false, + oldClrType: typeof(Guid), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 8) + .OldAnnotation("Relational:ColumnOrder", 7); + + migrationBuilder.AddColumn( + name: "WasCycleActive", + table: "ScheduledJobExecutions", + type: "INTEGER", + nullable: false, + defaultValue: false) + .Annotation("Relational:ColumnOrder", 6); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "WasCycleActive", + table: "ScheduledJobExecutions"); + + migrationBuilder.AlterColumn( + name: "UpdatedOnUtc", + table: "ScheduledJobExecutions", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateTime), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 8) + .OldAnnotation("Relational:ColumnOrder", 9); + + migrationBuilder.AlterColumn( + name: "UpdatedBy", + table: "ScheduledJobExecutions", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 9) + .OldAnnotation("Relational:ColumnOrder", 10); + + migrationBuilder.AlterColumn( + name: "CreatedOnUtc", + table: "ScheduledJobExecutions", + type: "TEXT", + nullable: false, + oldClrType: typeof(DateTime), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 6) + .OldAnnotation("Relational:ColumnOrder", 7); + + migrationBuilder.AlterColumn( + name: "CreatedBy", + table: "ScheduledJobExecutions", + type: "TEXT", + nullable: false, + oldClrType: typeof(Guid), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 7) + .OldAnnotation("Relational:ColumnOrder", 8); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs index 746a9146..79d0b407 100644 --- a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs +++ b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs @@ -1082,6 +1082,182 @@ namespace Lumina.DataAccess.Common.Migrations b.ToTable("Plugins", (string)null); }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Hour") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("IntervalMinutes") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("LastCompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastStartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Minute") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("OwnerUserId") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ScheduleType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.ToTable("ScheduledJobs", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobExecutionEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("IsCycleRun") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ScheduledJobId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("WasCycleActive") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("ScheduledJobId"); + + b.HasIndex("StartedOnUtc", "ScheduledJobId"); + + b.ToTable("ScheduledJobExecutions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.SchedulerDisplayPreferencesEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayTimeSpan") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("DisplayTimeUnit") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("JobTypeFilter") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("SchedulerDisplayPreferences", (string)null); + }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => { b.Property("Id") @@ -1257,14 +1433,14 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("INTEGER") .HasColumnOrder(4); - b.Property("ShouldRenderPdfAsImages") - .HasColumnType("INTEGER") - .HasColumnOrder(11); - b.Property("ShouldPreserveBookStyles") .HasColumnType("INTEGER") .HasColumnOrder(12); + b.Property("ShouldRenderPdfAsImages") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + b.Property("UpdatedBy") .HasColumnType("TEXT") .HasColumnOrder(8); diff --git a/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobExecutionRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobExecutionRepository.cs new file mode 100644 index 00000000..32f4fa45 --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobExecutionRepository.cs @@ -0,0 +1,139 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.Core.Repositories.Scheduling; + +/// +/// Repository for the executions of the tasks of scheduled jobs. +/// +internal sealed class ScheduledJobExecutionRepository : IScheduledJobExecutionRepository +{ + private readonly LuminaDbContext _luminaDbContext; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + public ScheduledJobExecutionRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// Gets an execution identified by from the storage medium. + /// + /// The id of the execution to get. + /// Cancellation token that can be used to stop the execution. + /// An containing either a identified by , or an error. + public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + { + // FindAsync returns an entity that was already loaded in the current unit of work from the change tracker, and only + // reads it from the storage medium when it is not tracked, so an entity loaded earlier is not read again. + return await _luminaDbContext.ScheduledJobExecutions.FindAsync([id], cancellationToken).ConfigureAwait(false); + } + + /// + /// Adds a new execution of the task of a scheduled job. + /// + /// The execution to add. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> InsertAsync(ScheduledJobExecutionEntity execution, CancellationToken cancellationToken) + { + bool doesExecutionExist = await _luminaDbContext.ScheduledJobExecutions.AnyAsync( + existingExecution => existingExecution.Id == execution.Id, cancellationToken).ConfigureAwait(false); + if (doesExecutionExist) + return Errors.Scheduling.ScheduledJobExecutionAlreadyExists; + + _luminaDbContext.ScheduledJobExecutions.Add(execution); + return Result.Created; + } + + /// + /// Updates an execution of the task of a scheduled job. + /// + /// The execution to update. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> UpdateAsync(ScheduledJobExecutionEntity data, CancellationToken cancellationToken) + { + ScheduledJobExecutionEntity? foundExecution = _luminaDbContext.ScheduledJobExecutions.Local.FirstOrDefault(execution => execution.Id == data.Id) + ?? await _luminaDbContext.ScheduledJobExecutions.FirstOrDefaultAsync(execution => execution.Id == data.Id, cancellationToken).ConfigureAwait(false); + if (foundExecution is null) + return Errors.Scheduling.ScheduledJobExecutionNotFound; + // Update scalar properties. + _luminaDbContext.Entry(foundExecution).CurrentValues.SetValues(data); + return Result.Updated; + } + + /// + /// Gets the most recent execution of the task of a scheduled job identified by that is still running, from the storage medium. + /// + /// The Id of the scheduled job whose running execution is retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the running execution of the scheduled job, or . + public async Task> GetOpenByScheduledJobIdAsync(Guid scheduledJobId, CancellationToken cancellationToken) + { + return await _luminaDbContext.ScheduledJobExecutions + .Where(execution => execution.ScheduledJobId == scheduledJobId && execution.CompletedOnUtc == null) + .OrderByDescending(execution => execution.StartedOnUtc) + .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets the executions of the tasks of scheduled jobs that started in the interval between and , from the storage medium. + /// + /// The inclusive lower bound of the interval, in UTC. + /// The inclusive upper bound of the interval, in UTC. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + public async Task>> GetByTimeRangeAsync(DateTime fromUtc, DateTime toUtc, CancellationToken cancellationToken) + { + return await _luminaDbContext.ScheduledJobExecutions + .Where(execution => execution.StartedOnUtc >= fromUtc && execution.StartedOnUtc <= toUtc) + .OrderBy(execution => execution.StartedOnUtc) + .ToListAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Removes all the executions of the task of a scheduled job identified by , from the storage medium. + /// + /// The Id of the scheduled job whose executions are removed. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteByScheduledJobIdAsync(Guid scheduledJobId, CancellationToken cancellationToken) + { + ScheduledJobExecutionEntity[] executions = await _luminaDbContext.ScheduledJobExecutions + .Where(execution => execution.ScheduledJobId == scheduledJobId) + .ToArrayAsync(cancellationToken).ConfigureAwait(false); + _luminaDbContext.ScheduledJobExecutions.RemoveRange(executions); + return Result.Success; + } + + /// + /// Removes all the executions of the tasks of scheduled jobs that started before , from the storage medium. + /// + /// The exclusive lower bound of the retained interval, in UTC; executions that started before it are removed. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteOlderThanAsync(DateTime cutoffUtc, CancellationToken cancellationToken) + { + // The executions are deleted with a single query, without loading them into memory first, because the retention cleanup + // routinely removes a large number of executions at once. + await _luminaDbContext.ScheduledJobExecutions + .Where(execution => execution.StartedOnUtc < cutoffUtc) + .ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false); + return Result.Success; + } +} diff --git a/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobRepository.cs new file mode 100644 index 00000000..899b05fb --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobRepository.cs @@ -0,0 +1,134 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.Core.Repositories.Scheduling; + +/// +/// Repository for scheduled jobs. +/// +internal sealed class ScheduledJobRepository : IScheduledJobRepository +{ + private readonly LuminaDbContext _luminaDbContext; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + public ScheduledJobRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// Gets a scheduled job identified by from the storage medium. + /// + /// The id of the scheduled job to get. + /// Cancellation token that can be used to stop the execution. + /// An containing either a identified by , or an error. + public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + { + // FindAsync returns an entity that was already loaded in the current unit of work from the change tracker, and only + // reads it from the storage medium when it is not tracked, so an entity loaded earlier is not read again. + return await _luminaDbContext.ScheduledJobs.FindAsync([id], cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets a scheduled job identified by from the storage medium, without tracking it. + /// + /// The id of the scheduled job to get. + /// Cancellation token that can be used to stop the execution. + /// An containing either a identified by , or an error. + public async Task> GetByIdWithoutTrackingAsync(Guid id, CancellationToken cancellationToken) + { + // The entity is read without tracking, so a concurrent update made by another unit of work is never hidden by an already tracked copy. + return await _luminaDbContext.ScheduledJobs + .AsNoTracking() + .FirstOrDefaultAsync(scheduledJob => scheduledJob.Id == id, cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets all scheduled jobs from the storage medium. + /// + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + public async Task>> GetAllAsync(CancellationToken cancellationToken) + { + return await _luminaDbContext.ScheduledJobs + .ToListAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets the scheduled jobs that have an active or running execution cycle, from the storage medium. + /// + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + public async Task>> GetActiveOrRunningAsync(CancellationToken cancellationToken) + { + return await _luminaDbContext.ScheduledJobs + .Where(scheduledJob => scheduledJob.Status == ScheduledJobStatus.Active || scheduledJob.Status == ScheduledJobStatus.Running) + .ToListAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Adds a new scheduled job. + /// + /// The scheduled job to add. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> InsertAsync(ScheduledJobEntity scheduledJob, CancellationToken cancellationToken) + { + bool doesScheduledJobExist = await _luminaDbContext.ScheduledJobs.AnyAsync( + existingScheduledJob => existingScheduledJob.Id == scheduledJob.Id, cancellationToken).ConfigureAwait(false); + if (doesScheduledJobExist) + return Errors.Scheduling.ScheduledJobAlreadyExists; + + _luminaDbContext.ScheduledJobs.Add(scheduledJob); + return Result.Created; + } + + /// + /// Updates a scheduled job. + /// + /// The scheduled job to update. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> UpdateAsync(ScheduledJobEntity data, CancellationToken cancellationToken) + { + ScheduledJobEntity? foundScheduledJob = _luminaDbContext.ScheduledJobs.Local.FirstOrDefault(scheduledJob => scheduledJob.Id == data.Id) + ?? await _luminaDbContext.ScheduledJobs.FirstOrDefaultAsync(scheduledJob => scheduledJob.Id == data.Id, cancellationToken).ConfigureAwait(false); + if (foundScheduledJob is null) + return Errors.Scheduling.ScheduledJobNotFound; + // Update scalar properties. + _luminaDbContext.Entry(foundScheduledJob).CurrentValues.SetValues(data); + return Result.Updated; + } + + /// + /// Removes a scheduled job identified by from the storage medium. + /// + /// The id of the scheduled job to remove. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteByIdAsync(Guid id, CancellationToken cancellationToken) + { + ScheduledJobEntity? foundScheduledJob = await _luminaDbContext.ScheduledJobs + .FirstOrDefaultAsync(scheduledJob => scheduledJob.Id == id, cancellationToken).ConfigureAwait(false); + if (foundScheduledJob is null) + return Errors.Scheduling.ScheduledJobNotFound; + + _luminaDbContext.ScheduledJobs.Remove(foundScheduledJob); + return Result.Deleted; + } +} diff --git a/src/Lumina.DataAccess/Core/Repositories/Scheduling/SchedulerDisplayPreferencesRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Scheduling/SchedulerDisplayPreferencesRepository.cs new file mode 100644 index 00000000..cb7ed707 --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/Scheduling/SchedulerDisplayPreferencesRepository.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +using Microsoft.EntityFrameworkCore; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.Core.Repositories.Scheduling; + +/// +/// Repository for the display preferences of the scheduler page. +/// +internal sealed class SchedulerDisplayPreferencesRepository : ISchedulerDisplayPreferencesRepository +{ + private readonly LuminaDbContext _luminaDbContext; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + public SchedulerDisplayPreferencesRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// Gets the display preferences of the scheduler page of the user identified by , if they exist. + /// + /// The Id of the user whose display preferences are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the display preferences of the user, or an error. + public async Task> GetByUserIdAsync(Guid userId, CancellationToken cancellationToken) + { + return await _luminaDbContext.SchedulerDisplayPreferences + .FirstOrDefaultAsync(preferences => preferences.UserId == userId, cancellationToken).ConfigureAwait(false); + } + + /// + /// Inserts the display preferences of the scheduler page of a user, or updates them when they already exist. + /// + /// The display preferences to insert or update. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> UpsertAsync(SchedulerDisplayPreferencesEntity preferences, CancellationToken cancellationToken) + { + SchedulerDisplayPreferencesEntity? existingPreferences = await _luminaDbContext.SchedulerDisplayPreferences + .FirstOrDefaultAsync(repositoryPreferences => repositoryPreferences.UserId == preferences.UserId, cancellationToken).ConfigureAwait(false); + if (existingPreferences is null) + _luminaDbContext.SchedulerDisplayPreferences.Add(preferences); + else + { + // Update only the mutable fields, preserving the Id and the ownership of the existing preferences. + existingPreferences.JobTypeFilter = preferences.JobTypeFilter; + existingPreferences.DisplayTimeSpan = preferences.DisplayTimeSpan; + existingPreferences.DisplayTimeUnit = preferences.DisplayTimeUnit; + } + return Result.Updated; + } +} diff --git a/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs b/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs index 6caf0fea..f37fceba 100644 --- a/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs +++ b/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs @@ -1,14 +1,14 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Common.DataAccess.Repositories.Authorization; -using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.Seed; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; using System; using System.Collections.Generic; using System.Threading; @@ -44,7 +44,7 @@ public class DataSeedService : IDataSeedService /// An representing either a successful operation, or an error. public async Task> SetDefaultAuthorizationPermissionsAsync(Guid adminId, CancellationToken cancellationToken) { - // create the default authorization permissions and add them to the repository. + // Create the default authorization permissions and add them to the repository. PermissionEntity[] defaultPermissions = [ new() { PermissionName = AuthorizationPermission.CanViewUsers, CreatedBy = adminId, CreatedOnUtc = _dateTimeProvider.UtcNow }, @@ -70,7 +70,7 @@ public class DataSeedService : IDataSeedService /// An representing either a successful operation, or an error. public async Task> SetDefaultAuthorizationRolesAsync(Guid userId, CancellationToken cancellationToken) { - // create the default authorization roles and add them to the repository + // Create the default authorization roles and add them to the repository. RoleEntity[] defaultRoles = [ new() { RoleName = "Admin", CreatedBy = userId, CreatedOnUtc = _dateTimeProvider.UtcNow } @@ -93,7 +93,7 @@ public class DataSeedService : IDataSeedService /// An representing either a successful operation, or an error. public async Task> SetAdminRolePermissionsAsync(Guid userId, CancellationToken cancellationToken) { - // get the admin role + // Get the admin role. Result getAdminRoleResult = await _unitOfWork.RoleRepository.GetByNameAsync("Admin", cancellationToken).ConfigureAwait(false); if (getAdminRoleResult.IsFailure) return getAdminRoleResult.Errors; @@ -101,12 +101,12 @@ public class DataSeedService : IDataSeedService if (getAdminRoleResult.Value is null) return Errors.Authorization.AdminAccountNotFound; - // get all permissions + // Get all permissions. Result> getPermissionsResult = await _unitOfWork.PermissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); if (getPermissionsResult.IsFailure) return getPermissionsResult.Errors; - // add each permission to the admin role + // Add each permission to the admin role. foreach (PermissionEntity permission in getPermissionsResult.Value) { RolePermissionEntity rolePermissionEntity = new() @@ -134,7 +134,7 @@ public class DataSeedService : IDataSeedService /// An representing either a successful operation, or an error. public async Task> SetAdminRoleToAdministratorAccount(Guid userId, CancellationToken cancellationToken) { - // get the admin role + // Get the admin role. Result getAdminRoleResult = await _unitOfWork.RoleRepository.GetByNameAsync("Admin", cancellationToken).ConfigureAwait(false); if (getAdminRoleResult.IsFailure) return getAdminRoleResult.Errors; @@ -142,7 +142,7 @@ public class DataSeedService : IDataSeedService if (getAdminRoleResult.Value is null) return Errors.Authorization.AdminRoleNotFound; - // get admin user + // Get admin user. Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure) return getUserResult.Errors; @@ -150,7 +150,7 @@ public class DataSeedService : IDataSeedService if (getUserResult.Value is null) return Errors.Authorization.AdminAccountNotFound; - // add the admin role to the admin user + // Add the admin role to the admin user. UserRoleEntity userRole = new() { CreatedBy = userId, @@ -167,4 +167,69 @@ public class DataSeedService : IDataSeedService await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return Result.Created; } + + /// + /// Sets up the default scheduled jobs, owned by the administrator account. + /// + /// The unique identifier of the administrator account that owns the default scheduled jobs. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> SetDefaultScheduledJobsAsync(Guid adminUserId, CancellationToken cancellationToken) + { + // Seed the default jobs. + ScheduledJobEntity[] defaultScheduledJobs = + [ + // Scan all the enabled media libraries, daily at midnight. + CreateDefaultScheduledJob("Daily media library scan", ScheduledTaskType.ScanMediaLibraries, ScheduleType.DailyAtHourAndMinute, intervalMinutes: null, hour: 0, minute: 0, adminUserId), + // Clean the temporary directory into which the reading plugins extract the books, at every application startup. + CreateDefaultScheduledJob("Clean temporary files at startup", ScheduledTaskType.CleanTemporaryFiles, ScheduleType.OnceAtStartup, intervalMinutes: null, hour: null, minute: null, adminUserId), + // Clean the temporary directory into which the reading plugins extract the books, every 12 hours. + CreateDefaultScheduledJob("Clean temporary files every 12 hours", ScheduledTaskType.CleanTemporaryFiles, ScheduleType.WithIntervalInMinutes, intervalMinutes: 720, hour: null, minute: null, adminUserId), + // Repair the installed themes whose files are missing, at every application startup. + CreateDefaultScheduledJob("Repair themes at startup", ScheduledTaskType.RepairThemes, ScheduleType.OnceAtStartup, intervalMinutes: null, hour: null, minute: null, adminUserId), + // Clean the execution history of the scheduled jobs, keeping only the executions of the past month, at every application startup. + CreateDefaultScheduledJob("Clean scheduled job execution history at startup", ScheduledTaskType.CleanScheduledJobExecutionHistory, ScheduleType.OnceAtStartup, intervalMinutes: null, hour: null, minute: null, adminUserId) + ]; + foreach (ScheduledJobEntity defaultScheduledJob in defaultScheduledJobs) + { + Result insertScheduledJobResult = await _unitOfWork.ScheduledJobRepository.InsertAsync(defaultScheduledJob, cancellationToken).ConfigureAwait(false); + if (insertScheduledJobResult.IsFailure) + return insertScheduledJobResult.Errors; + } + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + return Result.Created; + } + + /// + /// Creates a default scheduled job with its execution cycle active, owned by the administrator account identified by . + /// + /// The name of the default scheduled job. + /// The type of the task executed by the default scheduled job. + /// The type of the schedule of the default scheduled job. + /// The interval in minutes of the schedule, when it is an interval schedule. + /// The hour of the schedule, when it is a daily schedule. + /// The minute of the schedule, when it is a daily schedule. + /// The unique identifier of the administrator account that owns the default scheduled job. + /// The created default scheduled job. + private ScheduledJobEntity CreateDefaultScheduledJob(string name, ScheduledTaskType taskType, ScheduleType scheduleType, int? intervalMinutes, int? hour, int? minute, Guid adminUserId) + { + return new ScheduledJobEntity + { + Id = Guid.NewGuid(), + Name = name, + TaskType = taskType, + ScheduleType = scheduleType, + IntervalMinutes = intervalMinutes, + Hour = hour, + Minute = minute, + Status = ScheduledJobStatus.Active, + OwnerUserId = adminUserId, + LastStartedOnUtc = null, + LastCompletedOnUtc = null, + CreatedOnUtc = _dateTimeProvider.UtcNow, + CreatedBy = adminUserId, + UpdatedOnUtc = null, + UpdatedBy = null + }; + } } diff --git a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs index 46c62e07..eb1f811e 100644 --- a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs +++ b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs @@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Entities.Themes; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Microsoft.EntityFrameworkCore; @@ -39,6 +40,9 @@ public class LuminaDbContext : DbContext public virtual DbSet Themes { get; set; } = null!; public virtual DbSet MediaContributors { get; set; } = null!; public virtual DbSet BookContributors { get; set; } = null!; + public virtual DbSet ScheduledJobs { get; set; } = null!; + public virtual DbSet ScheduledJobExecutions { get; set; } = null!; + public virtual DbSet SchedulerDisplayPreferences { get; set; } = null!; /// /// Initializes a new instance of the class. @@ -54,7 +58,7 @@ public class LuminaDbContext : DbContext /// The model builder used to configure the entity mappings. protected override void OnModelCreating(ModelBuilder modelBuilder) { - // find all the entity configurations in the assembly and apply them + // Find all the entity configurations in the assembly and apply them. modelBuilder.ApplyConfigurationsFromAssembly(typeof(LuminaDbContext).Assembly); base.OnModelCreating(modelBuilder); diff --git a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs index b0260bff..e432f7be 100644 --- a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs +++ b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs @@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Repositories.Books; using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Themes; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; @@ -12,6 +13,7 @@ using Lumina.DataAccess.Core.Repositories.Books; using Lumina.DataAccess.Core.Repositories.Libraries; using Lumina.DataAccess.Core.Repositories.MediaContributors; using Lumina.DataAccess.Core.Repositories.Plugins; +using Lumina.DataAccess.Core.Repositories.Scheduling; using Lumina.DataAccess.Core.Repositories.Themes; using Lumina.DataAccess.Core.Repositories.Users; using Microsoft.EntityFrameworkCore.Storage; @@ -44,6 +46,9 @@ public class UnitOfWork : IUnitOfWork, IDisposable private ILibraryMetadataProviderConfigurationRepository? _libraryMetadataProviderConfigurationRepository; private IArtworkProviderConfigurationRepository? _artworkProviderConfigurationRepository; private ILibraryBookReaderConfigurationRepository? _libraryBookReaderConfigurationRepository; + private IScheduledJobRepository? _scheduledJobRepository; + private IScheduledJobExecutionRepository? _scheduledJobExecutionRepository; + private ISchedulerDisplayPreferencesRepository? _schedulerDisplayPreferencesRepository; private IPluginRepository? _pluginRepository; private IThemeRepository? _themeRepository; private IUserRepository? _userRepository; @@ -214,6 +219,42 @@ public class UnitOfWork : IUnitOfWork, IDisposable } } + /// + /// Gets the scheduled job repository. + /// + public IScheduledJobRepository ScheduledJobRepository + { + get + { + _scheduledJobRepository ??= new ScheduledJobRepository(_luminaDbContext); + return _scheduledJobRepository; + } + } + + /// + /// Gets the scheduled job execution repository. + /// + public IScheduledJobExecutionRepository ScheduledJobExecutionRepository + { + get + { + _scheduledJobExecutionRepository ??= new ScheduledJobExecutionRepository(_luminaDbContext); + return _scheduledJobExecutionRepository; + } + } + + /// + /// Gets the scheduler display preferences repository. + /// + public ISchedulerDisplayPreferencesRepository SchedulerDisplayPreferencesRepository + { + get + { + _schedulerDisplayPreferencesRepository ??= new SchedulerDisplayPreferencesRepository(_luminaDbContext); + return _schedulerDisplayPreferencesRepository; + } + } + /// /// Gets the plugin repository. /// diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/ScheduleType.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/ScheduleType.cs new file mode 100644 index 00000000..34454e08 --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/ScheduleType.cs @@ -0,0 +1,22 @@ +namespace Lumina.Domain.SharedKernel.Common.Enums.Scheduling; + +/// +/// Enumeration for the types of schedules of scheduled jobs. +/// +public enum ScheduleType +{ + /// + /// The scheduled job repeats with an interval measured in minutes. + /// + WithIntervalInMinutes, + + /// + /// The scheduled job repeats daily at a fixed hour and minute. + /// + DailyAtHourAndMinute, + + /// + /// The scheduled job fires its task once, every time the application starts. + /// + OnceAtStartup +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/ScheduledJobStatus.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/ScheduledJobStatus.cs new file mode 100644 index 00000000..f8d84191 --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/ScheduledJobStatus.cs @@ -0,0 +1,27 @@ +namespace Lumina.Domain.SharedKernel.Common.Enums.Scheduling; + +/// +/// Enumeration for the statuses of scheduled jobs. +/// +public enum ScheduledJobStatus +{ + /// + /// The scheduled job was added, but its execution cycle was not started. + /// + Added, + + /// + /// The execution cycle of the scheduled job is active, and the job is waiting for its next scheduled execution. + /// + Active, + + /// + /// The task of the scheduled job is currently being executed. + /// + Running, + + /// + /// The scheduled job finished its latest one time execution. + /// + Completed +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/ScheduledTaskType.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/ScheduledTaskType.cs new file mode 100644 index 00000000..cc91f3cc --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/ScheduledTaskType.cs @@ -0,0 +1,27 @@ +namespace Lumina.Domain.SharedKernel.Common.Enums.Scheduling; + +/// +/// Enumeration for the types of tasks a scheduled job can execute. +/// +public enum ScheduledTaskType +{ + /// + /// The scheduled job scans all enabled media libraries. + /// + ScanMediaLibraries, + + /// + /// The scheduled job cleans the temporary directory of the application. + /// + CleanTemporaryFiles, + + /// + /// The scheduled job repairs the installed themes whose files are missing. + /// + RepairThemes, + + /// + /// The scheduled job cleans the execution history of the scheduled jobs, keeping only the recent executions. + /// + CleanScheduledJobExecutionHistory +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/SchedulerDisplayTimeUnit.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/SchedulerDisplayTimeUnit.cs new file mode 100644 index 00000000..d23e525e --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/SchedulerDisplayTimeUnit.cs @@ -0,0 +1,22 @@ +namespace Lumina.Domain.SharedKernel.Common.Enums.Scheduling; + +/// +/// Enumeration for the units in which the display time span of the scheduler page is expressed. +/// +public enum SchedulerDisplayTimeUnit +{ + /// + /// The display time span is expressed in minutes. + /// + Minutes, + + /// + /// The display time span is expressed in hours. + /// + Hours, + + /// + /// The display time span is expressed in days. + /// + Days +} diff --git a/src/Lumina.Domain/Common/Errors/Errors.Scheduling.cs b/src/Lumina.Domain/Common/Errors/Errors.Scheduling.cs new file mode 100644 index 00000000..e20fd6f6 --- /dev/null +++ b/src/Lumina.Domain/Common/Errors/Errors.Scheduling.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +#endregion + +namespace Lumina.Domain.Common.Errors; + +/// +/// Scheduled job error types. +/// +public static partial class Errors +{ + public static class Scheduling + { + public static Error ScheduledJobNameCannotBeEmpty => Error.Validation(description: nameof(ScheduledJobNameCannotBeEmpty)); + public static Error IntervalMinutesMustBePositive => Error.Validation(description: nameof(IntervalMinutesMustBePositive)); + public static Error HourMustBeBetweenZeroAndTwentyThree => Error.Validation(description: nameof(HourMustBeBetweenZeroAndTwentyThree)); + public static Error MinuteMustBeBetweenZeroAndFiftyNine => Error.Validation(description: nameof(MinuteMustBeBetweenZeroAndFiftyNine)); + public static Error ScheduledJobAlreadyExists => Error.Conflict(description: nameof(ScheduledJobAlreadyExists)); + public static Error ScheduledJobNotFound => Error.NotFound(description: nameof(ScheduledJobNotFound)); + public static Error ScheduledJobExecutionAlreadyExists => Error.Conflict(description: nameof(ScheduledJobExecutionAlreadyExists)); + public static Error ScheduledJobExecutionNotFound => Error.NotFound(description: nameof(ScheduledJobExecutionNotFound)); + public static Error ScheduledJobCycleAlreadyStarted => Error.Forbidden(description: nameof(ScheduledJobCycleAlreadyStarted)); + public static Error ScheduledJobNotStarted => Error.Forbidden(description: nameof(ScheduledJobNotStarted)); + public static Error ScheduledJobAlreadyRunning => Error.Forbidden(description: nameof(ScheduledJobAlreadyRunning)); + public static Error CanOnlyCompleteRunningScheduledJob => Error.Forbidden(description: nameof(CanOnlyCompleteRunningScheduledJob)); + public static Error InvalidScheduleType => Error.Validation(description: nameof(InvalidScheduleType)); + public static Error SchedulerDisplayTimeSpanMustBePositive => Error.Validation(description: nameof(SchedulerDisplayTimeSpanMustBePositive)); + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserId.cs b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserId.cs new file mode 100644 index 00000000..8af9c718 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserId.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; + +/// +/// Value object for the Id of a user, duplicated from the UserManagement bounded context to keep the cross bounded context references decoupled. +/// +[DebuggerDisplay("{Value}")] +public sealed class UserId : EntityId +{ + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + private UserId(Guid value) : base(value) + { + } + + /// + /// Creates a new instance of the class. + /// + /// The created instance. + public static UserId CreateUnique() + { + return new UserId(Guid.NewGuid()); + } + + /// + /// Creates a new instance of the class, from a pre-existing . + /// + /// The value used to create the instance. + /// The created instance. + public static UserId Create(Guid value) + { + return new UserId(value); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Value; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobAddedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobAddedDomainEvent.cs new file mode 100644 index 00000000..88430a4a --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobAddedDomainEvent.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; + +/// +/// Domain event raised when a scheduled job is added. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the scheduled job that was added. +/// The date and time when the domain event occurred. +[DebuggerDisplay("Id: {ScheduledJobId.Value}")] +public record ScheduledJobAddedDomainEvent( + Guid Id, + ScheduledJobId ScheduledJobId, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobCycleStartedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobCycleStartedDomainEvent.cs new file mode 100644 index 00000000..a361b456 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobCycleStartedDomainEvent.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; + +/// +/// Domain event raised when the execution cycle of a scheduled job is started. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the scheduled job whose execution cycle was started. +/// The date and time when the domain event occurred. +[DebuggerDisplay("Id: {ScheduledJobId.Value}")] +public record ScheduledJobCycleStartedDomainEvent( + Guid Id, + ScheduledJobId ScheduledJobId, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobCycleStoppedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobCycleStoppedDomainEvent.cs new file mode 100644 index 00000000..584f6246 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobCycleStoppedDomainEvent.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; + +/// +/// Domain event raised when the execution cycle of a scheduled job is stopped. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the scheduled job whose execution cycle was stopped. +/// The date and time when the domain event occurred. +[DebuggerDisplay("Id: {ScheduledJobId.Value}")] +public record ScheduledJobCycleStoppedDomainEvent( + Guid Id, + ScheduledJobId ScheduledJobId, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobExecutionCompletedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobExecutionCompletedDomainEvent.cs new file mode 100644 index 00000000..de7f97df --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobExecutionCompletedDomainEvent.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; + +/// +/// Domain event raised when the task of a scheduled job completes its execution. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the scheduled job whose task completed its execution. +/// The unique identifier of the current execution of the task of the scheduled job. +/// The type of the task that completed its execution. +/// when the execution was triggered by the execution cycle of the scheduled job, when it was a one time execution. +/// The date and time when the execution completed. +[DebuggerDisplay("Id: {ScheduledJobId.Value}, RunId: {RunId}")] +public record ScheduledJobExecutionCompletedDomainEvent( + Guid Id, + ScheduledJobId ScheduledJobId, + Guid RunId, + ScheduledTaskType TaskType, + bool IsCycleRun, + DateTime CompletedOnUtc +) : IDomainEvent +{ + /// + /// Gets the date and time when the domain event occurred. + /// + public DateTime OccurredOnUtc => CompletedOnUtc; +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobExecutionStartedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobExecutionStartedDomainEvent.cs new file mode 100644 index 00000000..e64611c0 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobExecutionStartedDomainEvent.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; + +/// +/// Domain event raised when the task of a scheduled job starts its execution. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the scheduled job whose task started executing. +/// The unique identifier of the current execution of the task of the scheduled job. +/// The type of the task that started executing. +/// when the execution was triggered by the execution cycle of the scheduled job, when it was a one time execution. +/// The date and time when the execution started. +[DebuggerDisplay("Id: {ScheduledJobId.Value}, RunId: {RunId}")] +public record ScheduledJobExecutionStartedDomainEvent( + Guid Id, + ScheduledJobId ScheduledJobId, + Guid RunId, + ScheduledTaskType TaskType, + bool IsCycleRun, + DateTime StartedOnUtc +) : IDomainEvent +{ + /// + /// Gets the date and time when the domain event occurred. + /// + public DateTime OccurredOnUtc => StartedOnUtc; +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobExecutionStoppedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobExecutionStoppedDomainEvent.cs new file mode 100644 index 00000000..fbf77e34 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobExecutionStoppedDomainEvent.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; + +/// +/// Domain event raised when the execution of the task of a scheduled job is stopped while it is running. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the scheduled job whose running execution was stopped. +/// The date and time when the domain event occurred. +[DebuggerDisplay("Id: {ScheduledJobId.Value}")] +public record ScheduledJobExecutionStoppedDomainEvent( + Guid Id, + ScheduledJobId ScheduledJobId, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobFiredDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobFiredDomainEvent.cs new file mode 100644 index 00000000..6f2f004d --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobFiredDomainEvent.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; + +/// +/// Domain event raised when the task of a scheduled job is fired once. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the scheduled job whose task was fired. +/// The date and time when the domain event occurred. +[DebuggerDisplay("Id: {ScheduledJobId.Value}")] +public record ScheduledJobFiredDomainEvent( + Guid Id, + ScheduledJobId ScheduledJobId, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobRemovedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobRemovedDomainEvent.cs new file mode 100644 index 00000000..9587fff9 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobRemovedDomainEvent.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; + +/// +/// Domain event raised when a scheduled job is removed. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the scheduled job that was removed. +/// The date and time when the domain event occurred. +[DebuggerDisplay("Id: {ScheduledJobId.Value}")] +public record ScheduledJobRemovedDomainEvent( + Guid Id, + ScheduledJobId ScheduledJobId, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ScheduledJob.cs b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ScheduledJob.cs new file mode 100644 index 00000000..067f5fdc --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ScheduledJob.cs @@ -0,0 +1,229 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; + +/// +/// Aggregate root for a scheduled job. +/// +[DebuggerDisplay("Id: {Id.Value}")] +public class ScheduledJob : AggregateRoot +{ + private Optional _currentExecutionRunId; + + /// + /// Gets the name of the scheduled job. + /// + public string Name { get; private set; } + + /// + /// Gets the type of the task executed by the scheduled job. + /// + public ScheduledTaskType TaskType { get; private set; } + + /// + /// Gets the schedule of the scheduled job. + /// + public Schedule Schedule { get; private set; } + + /// + /// Gets the status of the scheduled job. + /// + public ScheduledJobStatus Status { get; private set; } + + /// + /// Gets the object representing the unique identifier of the user that owns the scheduled job. + /// + public UserId OwnerUserId { get; private set; } + + /// + /// Gets the optional date and time when the task of the scheduled job last started its execution. + /// + public Optional LastStartedOnUtc { get; private set; } + + /// + /// Gets the optional date and time when the task of the scheduled job last completed its execution. + /// + public Optional LastCompletedOnUtc { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The object representing the unique identifier of the scheduled job. + /// The name of the scheduled job. + /// The type of the task executed by the scheduled job. + /// The schedule of the scheduled job. + /// The object representing the unique identifier of the user that owns the scheduled job. + /// The status of the scheduled job. + /// The optional date and time when the task of the scheduled job last started its execution. + /// The optional date and time when the task of the scheduled job last completed its execution. + private ScheduledJob(ScheduledJobId id, string name, ScheduledTaskType taskType, Schedule schedule, UserId ownerUserId, ScheduledJobStatus status, Optional lastStartedOnUtc, Optional lastCompletedOnUtc) + : base(id) + { + Name = name; + TaskType = taskType; + Schedule = schedule; + OwnerUserId = ownerUserId; + Status = status; + LastStartedOnUtc = lastStartedOnUtc; + LastCompletedOnUtc = lastCompletedOnUtc; + _currentExecutionRunId = Optional.None(); + } + + /// + /// Creates a new instance of the class. + /// + /// The name of the scheduled job. + /// The type of the task executed by the scheduled job. + /// The schedule of the scheduled job. + /// The object representing the unique identifier of the user that owns the scheduled job. + /// + /// An containing either a successfully created , or an error message. + /// + public static Result Create(string name, ScheduledTaskType taskType, Schedule schedule, UserId ownerUserId) + { + if (string.IsNullOrWhiteSpace(name)) + return Errors.Scheduling.ScheduledJobNameCannotBeEmpty; + return new ScheduledJob(ScheduledJobId.CreateUnique(), name, taskType, schedule, ownerUserId, ScheduledJobStatus.Added, Optional.None(), Optional.None()); + } + + /// + /// Creates a new instance of the class, with pre-existing data. + /// + /// The object representing the unique identifier of the scheduled job. + /// The name of the scheduled job. + /// The type of the task executed by the scheduled job. + /// The schedule of the scheduled job. + /// The object representing the unique identifier of the user that owns the scheduled job. + /// The status of the scheduled job. + /// The optional date and time when the task of the scheduled job last started its execution. + /// The optional date and time when the task of the scheduled job last completed its execution. + /// + /// An containing either a successfully created , or an error message. + /// + public static Result Create(ScheduledJobId id, string name, ScheduledTaskType taskType, Schedule schedule, UserId ownerUserId, ScheduledJobStatus status, Optional lastStartedOnUtc, Optional lastCompletedOnUtc) + { + if (string.IsNullOrWhiteSpace(name)) + return Errors.Scheduling.ScheduledJobNameCannotBeEmpty; + return new ScheduledJob(id, name, taskType, schedule, ownerUserId, status, lastStartedOnUtc, lastCompletedOnUtc); + } + + /// + /// Marks the scheduled job as added. + /// + /// An representing either a successful operation, or an error. + public Result Add() + { + if (Status != ScheduledJobStatus.Added) + return Errors.Scheduling.ScheduledJobCycleAlreadyStarted; + _domainEvents.Add(new ScheduledJobAddedDomainEvent(Guid.NewGuid(), Id, DateTime.UtcNow)); + return Result.Success; + } + + /// + /// Starts the execution cycle of the scheduled job. + /// + /// An representing either a successful operation, or an error. + public Result StartCycle() + { + if (Status == ScheduledJobStatus.Active || Status == ScheduledJobStatus.Running) + return Errors.Scheduling.ScheduledJobCycleAlreadyStarted; + + Status = ScheduledJobStatus.Active; + _domainEvents.Add(new ScheduledJobCycleStartedDomainEvent(Guid.NewGuid(), Id, DateTime.UtcNow)); + return Result.Success; + } + + /// + /// Stops the execution cycle of the scheduled job. + /// + /// An representing either a successful operation, or an error. + public Result StopCycle() + { + if (Status == ScheduledJobStatus.Added || Status == ScheduledJobStatus.Completed) + return Errors.Scheduling.ScheduledJobNotStarted; + + ScheduledJobStatus previousStatus = Status; + Status = ScheduledJobStatus.Added; + + // When the task of the scheduled job is currently executing, its execution is stopped as well, so its history row is closed. + if (previousStatus == ScheduledJobStatus.Running) + { + LastCompletedOnUtc = Optional.Some(DateTime.UtcNow); + _domainEvents.Add(new ScheduledJobExecutionStoppedDomainEvent(Guid.NewGuid(), Id, DateTime.UtcNow)); + } + else + _domainEvents.Add(new ScheduledJobCycleStoppedDomainEvent(Guid.NewGuid(), Id, DateTime.UtcNow)); + return Result.Success; + } + + /// + /// Marks the start of a one time execution of the task of the scheduled job. + /// + /// An representing either a successful operation, or an error. + public Result Fire() + { + if (Status == ScheduledJobStatus.Running) + return Errors.Scheduling.ScheduledJobAlreadyRunning; + _domainEvents.Add(new ScheduledJobFiredDomainEvent(Guid.NewGuid(), Id, DateTime.UtcNow)); + return Result.Success; + } + + /// + /// Marks the scheduled job as removed. + /// + /// An representing either a successful operation, or an error. + public Result Remove() + { + _domainEvents.Add(new ScheduledJobRemovedDomainEvent(Guid.NewGuid(), Id, DateTime.UtcNow)); + return Result.Success; + } + + /// + /// Marks the task of the scheduled job as started. + /// + /// Whether the execution was triggered by the execution cycle of the scheduled job, or it is a one time execution. + /// An representing either a successful operation, or an error. + public Result MarkExecutionStarted(bool isCycleRun) + { + if (Status == ScheduledJobStatus.Running) + return Errors.Scheduling.ScheduledJobAlreadyRunning; + + Guid runId = Guid.NewGuid(); + _currentExecutionRunId = Optional.Some(runId); + Status = ScheduledJobStatus.Running; + LastStartedOnUtc = Optional.Some(DateTime.UtcNow); + _domainEvents.Add(new ScheduledJobExecutionStartedDomainEvent(Guid.NewGuid(), Id, runId, TaskType, isCycleRun, DateTime.UtcNow)); + return Result.Success; + } + + /// + /// Marks the task of the scheduled job as completed. + /// + /// Whether the execution was triggered by the execution cycle of the scheduled job, or it is a one time execution. + /// An representing either a successful operation, or an error. + public Result MarkExecutionCompleted(bool isCycleRun) + { + if (Status != ScheduledJobStatus.Running) + return Errors.Scheduling.CanOnlyCompleteRunningScheduledJob; + if (!_currentExecutionRunId.HasValue) + return Errors.Scheduling.CanOnlyCompleteRunningScheduledJob; + + Guid runId = _currentExecutionRunId.Value; + _currentExecutionRunId = Optional.None(); + // A cycle run returns the scheduled job to its active state, where it waits for the next execution; a one time execution finishes the scheduled job. + Status = isCycleRun ? ScheduledJobStatus.Active : ScheduledJobStatus.Completed; + LastCompletedOnUtc = Optional.Some(DateTime.UtcNow); + _domainEvents.Add(new ScheduledJobExecutionCompletedDomainEvent(Guid.NewGuid(), Id, runId, TaskType, isCycleRun, DateTime.UtcNow)); + return Result.Success; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/DailySchedule.cs b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/DailySchedule.cs new file mode 100644 index 00000000..2b63fe38 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/DailySchedule.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; + +/// +/// Value Object for the daily schedule for a scheduled job. +/// +public class DailySchedule : Schedule +{ + /// + /// Gets the hour of the day at which the scheduled job runs. + /// + public int Hour { get; } + + /// + /// Gets the minute of the hour at which the scheduled job runs. + /// + public int Minute { get; } + + /// + /// Gets the type of the schedule. + /// + public override ScheduleType ScheduleType { get; } = ScheduleType.DailyAtHourAndMinute; + + /// + /// Initializes a new instance of the class. + /// + /// The hour of the day at which the scheduled job runs. + /// The minute of the hour at which the scheduled job runs. + private DailySchedule(int hour, int minute) + { + Hour = hour; + Minute = minute; + } + + /// + /// Creates a new instance of the class. + /// + /// The hour of the day at which the scheduled job runs. + /// The minute of the hour at which the scheduled job runs. + /// + /// An containing either a successfully created , or an error message. + /// + public static Result Create(int hour, int minute) + { + if (hour < 0 || hour > 23) + return Errors.Scheduling.HourMustBeBetweenZeroAndTwentyThree; + if (minute < 0 || minute > 59) + return Errors.Scheduling.MinuteMustBeBetweenZeroAndFiftyNine; + return new DailySchedule(hour, minute); + } + + /// + /// Calculates the delay until the next execution of the scheduled job, relative to . + /// + /// The current UTC date and time. + /// The time zone in which the daily hour and minute of the schedule are expressed. + /// The delay until the next execution of the scheduled job. + public override TimeSpan GetDelayUntilNextExecution(DateTime utcNow, TimeZoneInfo timeZone) + { + DateTime localNow = TimeZoneInfo.ConvertTimeFromUtc(utcNow, timeZone); + DateTime nextRunLocal = new(localNow.Year, localNow.Month, localNow.Day, Hour, Minute, 0, DateTimeKind.Unspecified); + DateTime nextRunUtc = TimeZoneInfo.ConvertTimeToUtc(nextRunLocal, timeZone); + // When the next run time already passed today, schedule the execution for the next day. + if (nextRunUtc <= utcNow) + nextRunUtc = nextRunUtc.AddDays(1); + return nextRunUtc - utcNow; + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Hour; + yield return Minute; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/IntervalSchedule.cs b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/IntervalSchedule.cs new file mode 100644 index 00000000..f4720474 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/IntervalSchedule.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; + +/// +/// Value Object for the interval based schedule for a scheduled job. +/// +public class IntervalSchedule : Schedule +{ + /// + /// Gets the interval of the schedule, in minutes. + /// + public int IntervalMinutes { get; } + + /// + /// Gets the type of the schedule. + /// + public override ScheduleType ScheduleType { get; } = ScheduleType.WithIntervalInMinutes; + + /// + /// Initializes a new instance of the class. + /// + /// The interval of the schedule, in minutes. + private IntervalSchedule(int intervalMinutes) + { + IntervalMinutes = intervalMinutes; + } + + /// + /// Creates a new instance of the class. + /// + /// The interval of the schedule, in minutes. + /// + /// An containing either a successfully created , or an error message. + /// + public static Result Create(int intervalMinutes) + { + if (intervalMinutes <= 0) + return Errors.Scheduling.IntervalMinutesMustBePositive; + return new IntervalSchedule(intervalMinutes); + } + + /// + /// Calculates the delay until the next execution of the scheduled job, relative to . + /// + /// The current UTC date and time. + /// The time zone in which the daily hour and minute of the schedule are expressed. + /// The delay until the next execution of the scheduled job. + public override TimeSpan GetDelayUntilNextExecution(DateTime utcNow, TimeZoneInfo timeZone) + { + return TimeSpan.FromMinutes(IntervalMinutes); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return IntervalMinutes; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/OnceAtStartupSchedule.cs b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/OnceAtStartupSchedule.cs new file mode 100644 index 00000000..c17c914d --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/OnceAtStartupSchedule.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; + +/// +/// Value Object for the schedule that fires the task of the scheduled job once, at every application startup. +/// +public class OnceAtStartupSchedule : Schedule +{ + /// + /// Gets the type of the schedule. + /// + public override ScheduleType ScheduleType { get; } = ScheduleType.OnceAtStartup; + + /// + /// Initializes a new instance of the class. + /// + private OnceAtStartupSchedule() + { + } + + /// + /// Creates a new instance of the class. + /// + /// + /// An containing either a successfully created , or an error message. + /// + public static Result Create() + { + return new OnceAtStartupSchedule(); + } + + /// + /// Calculates the delay until the next execution of the scheduled job, relative to . + /// + /// The current UTC date and time. + /// The time zone in which the daily hour and minute of the schedule are expressed. + /// The delay until the next execution of the scheduled job. + /// + /// A once at startup schedule has no further execution after the one fired at the application startup, so the scheduler + /// never calls this method for it; a maximum delay is returned so that the contract stays total. + /// + public override TimeSpan GetDelayUntilNextExecution(DateTime utcNow, TimeZoneInfo timeZone) + { + return TimeSpan.MaxValue; + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield break; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/Schedule.cs b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/Schedule.cs new file mode 100644 index 00000000..e14d3eeb --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/Schedule.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; + +/// +/// Value Object for the abstract schedule for a scheduled job. +/// +public abstract class Schedule : ValueObject +{ + /// + /// Gets the type of the schedule. + /// + public abstract ScheduleType ScheduleType { get; } + + /// + /// Calculates the delay until the next execution of the scheduled job, relative to . + /// + /// The current UTC date and time. + /// The time zone in which the daily hour and minute of the schedule are expressed. + /// The delay until the next execution of the scheduled job. + public abstract TimeSpan GetDelayUntilNextExecution(DateTime utcNow, TimeZoneInfo timeZone); +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/ScheduledJobId.cs b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/ScheduledJobId.cs new file mode 100644 index 00000000..c6dcbdce --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/ScheduledJobId.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; + +/// +/// Value Object for the Id of a scheduled job. +/// +[DebuggerDisplay("{Value}")] +public sealed class ScheduledJobId : EntityId +{ + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + private ScheduledJobId(Guid value) : base(value) + { + } + + /// + /// Creates a new instance of the class. + /// + /// The created instance. + public static ScheduledJobId CreateUnique() + { + return new ScheduledJobId(Guid.NewGuid()); + } + + /// + /// Creates a new instance of the class, from a pre-existing . + /// + /// The value used to create the instance. + /// The created instance. + public static ScheduledJobId Create(Guid value) + { + return new ScheduledJobId(value); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Value; + } +} diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index 39fc1f8a..7e857371 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -8,12 +8,14 @@ using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; using Lumina.Application.Common.Infrastructure.Plugins; using Lumina.Application.Common.Infrastructure.Reading; using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Application.Common.Infrastructure.Scheduling; using Lumina.Application.Common.Infrastructure.Themes; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.Management.Progress; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Lumina.Application.Core.Scheduling.Notifications; using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; @@ -34,6 +36,9 @@ using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue; using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; using Lumina.Infrastructure.Core.Plugins; +using Lumina.Infrastructure.Core.Scheduling.Execution; +using Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors; +using Lumina.Infrastructure.Core.Scheduling.Notifications; using Lumina.Infrastructure.Core.Security; using Lumina.Infrastructure.Core.Themes; using Lumina.Infrastructure.Core.Time; @@ -113,8 +118,8 @@ public static class InfrastructureLayerServices services.AddHttpClient(); services.AddScoped(); - // Book reading: resolves the book reader plugins, extracts the books into a temporary directory, and serves their contents; - // the enablement cache lets the reading service skip the per-request database read of the reader configurations. + // Book reading: resolves the book reader plugins, extracts the books into a temporary directory, and serves their contents. + // The enablement cache lets the reading service skip the per-request database read of the reader configurations. services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); @@ -134,9 +139,20 @@ public static class InfrastructureLayerServices serviceProvider.GetRequiredService>())); services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService()); - // Themes: the theme service stores and serves theme packs, and the detection job seeds the bundled themes at startup. + // Themes: the theme service stores and serves theme packs; the bundled themes are installed and repaired by the + // default "Repair themes at startup" scheduled job that is seeded when the application is set up. services.AddSingleton(); - services.AddHostedService(); + + // Scheduled jobs: the scheduler executes the tasks of the scheduled jobs on their schedules, and the notifier broadcasts their state to the SignalR clients. + services.AddSingleton(); + services.AddHostedService(serviceProvider => (ScheduledJobSchedulerJob)serviceProvider.GetRequiredService()); + services.AddSingleton(); + services.AddSingleton(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); return services; } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Progress/MediaLibraryScanProgressHub.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Progress/MediaLibraryScanProgressHub.cs index f25109ee..53cbd933 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Progress/MediaLibraryScanProgressHub.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Progress/MediaLibraryScanProgressHub.cs @@ -1,6 +1,10 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.SignalR; using System; +using System.Security.Claims; using System.Threading.Tasks; #endregion @@ -9,15 +13,20 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress; /// /// SignalR hub for managing real-time media library scan progress updates. /// +[Authorize] public class MediaLibraryScanProgressHub : Hub { /// /// Subscribes the current connection to scan progress notifications for a specific scan operation. /// /// Unique identifier of the scan operation. - /// Unique identifier of the requesting user. - public async Task SubscribeToScan(Guid scanId, Guid userId) + public async Task SubscribeToScan(Guid scanId) { - await Groups.AddToGroupAsync(Context.ConnectionId, $"{scanId}-{userId}"); + // The user is never taken from the client, because any client could otherwise subscribe to the progress of a scan by claiming another user's identifier. + // The user is taken from the authenticated connection instead. + string? userIdClaim = Context.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value; + if (!Guid.TryParse(userIdClaim, out Guid userId)) + return; + await Groups.AddToGroupAsync(Context.ConnectionId, MediaLibraryScanCompositeId.Create(ScanId.Create(scanId), UserId.Create(userId)).ToString()); } } diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledJobCycleTicker.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledJobCycleTicker.cs new file mode 100644 index 00000000..b25a91a3 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledJobCycleTicker.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Execution; + +/// +/// Represents a cancellable periodic ticker that drives the cadence of an execution cycle of a scheduled job. +/// +/// +/// The interface is separated from the periodic timer it wraps so that the unit tests of the cycle worker can drive +/// the cadence with a stubbed ticker, instead of waiting on the real periodic timer, whose periods start at one minute. +/// +internal interface IScheduledJobCycleTicker : IDisposable +{ + /// + /// Sets the period between the ticks of the ticker. + /// + /// + /// The period of a daily schedule is recalculated after every run from the current time, so it is assigned after each tick. + /// + TimeSpan Period { set; } + + /// + /// Waits until the next tick of the ticker, or until the ticker is disposed or is cancelled. + /// + /// Cancellation token that can be used to stop the wait. + /// when a tick occurred; when the ticker was disposed before the next tick. + ValueTask WaitForNextTickAsync(CancellationToken cancellationToken); +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledJobRuntimeRegistry.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledJobRuntimeRegistry.cs new file mode 100644 index 00000000..de8ade8b --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledJobRuntimeRegistry.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using System.Threading; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Execution; + +/// +/// Interface for the registry that holds the live runtime state of the scheduled jobs. +/// +public interface IScheduledJobRuntimeRegistry +{ + /// + /// Starts the execution cycle of the scheduled job identified by . + /// + /// The object representing the unique identifier of the scheduled job whose cycle is started. + /// The cancellation token source used to stop the execution cycle. + /// when the cycle was started, when a cycle was already running. + bool TryStartCycle(ScheduledJobId scheduledJobId, CancellationTokenSource cycleCancellationTokenSource); + + /// + /// Gets a value indicating whether the execution cycle of the scheduled job identified by is currently running. + /// + /// The object representing the unique identifier of the scheduled job whose cycle is checked. + /// when a cycle is currently running, otherwise. + bool HasActiveCycle(ScheduledJobId scheduledJobId); + + /// + /// Stops the execution cycle of the scheduled job identified by . + /// + /// The object representing the unique identifier of the scheduled job whose cycle is stopped. + void StopCycle(ScheduledJobId scheduledJobId); + + /// + /// Ends the execution cycle of the scheduled job identified by , when it was started with . + /// + /// The object representing the unique identifier of the scheduled job whose cycle is ended. + /// The cancellation token source of the cycle that is ending. + void EndCycle(ScheduledJobId scheduledJobId, CancellationTokenSource cycleCancellationTokenSource); + + /// + /// Attempts to reserve the execution slot of the scheduled job identified by . + /// + /// The object representing the unique identifier of the scheduled job whose execution slot is reserved. + /// when the slot was reserved, when another execution is already running. + bool TryAcquireRunSlot(ScheduledJobId scheduledJobId); + + /// + /// Releases the execution slot of the scheduled job identified by . + /// + /// The object representing the unique identifier of the scheduled job whose execution slot is released. + void ReleaseRunSlot(ScheduledJobId scheduledJobId); +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledTaskExecutor.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledTaskExecutor.cs new file mode 100644 index 00000000..98de6300 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledTaskExecutor.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Execution; + +/// +/// Interface for the executor of the task of a scheduled job. +/// +public interface IScheduledTaskExecutor +{ + /// + /// Executes the payload of the task of the scheduled job, asynchronously. + /// + /// The scheduled job whose task is executed. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> ExecutePayloadAsync(ScheduledJob scheduledJob, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledTaskExecutorFactory.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledTaskExecutorFactory.cs new file mode 100644 index 00000000..15358b1f --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledTaskExecutorFactory.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Execution; + +/// +/// Interface for the factory that creates the executor of the task of a scheduled job, based on the type of its task. +/// +public interface IScheduledTaskExecutorFactory +{ + /// + /// Creates the executor of the task of a scheduled job, based on the type of its task. + /// + /// The type of the task whose executor is created. + /// The created task executor. + IScheduledTaskExecutor CreateExecutor(ScheduledTaskType taskType); +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/PeriodicScheduledJobCycleTicker.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/PeriodicScheduledJobCycleTicker.cs new file mode 100644 index 00000000..b7c788ff --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/PeriodicScheduledJobCycleTicker.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Execution; + +/// +/// Default implementation that ticks on a . +/// +internal sealed class PeriodicScheduledJobCycleTicker : IScheduledJobCycleTicker +{ + private readonly PeriodicTimer _periodicTimer; + + /// + /// Initializes a new instance of the class. + /// + /// The period between the ticks of the ticker. + public PeriodicScheduledJobCycleTicker(TimeSpan period) + { + _periodicTimer = new PeriodicTimer(period); + } + + /// + /// Sets the period between the ticks of the ticker. + /// + public TimeSpan Period + { + set + { + _periodicTimer.Period = value; + } + } + + /// + /// Waits until the next tick of the ticker, or until the ticker is disposed or is cancelled. + /// + /// Cancellation token that can be used to stop the wait. + /// when a tick occurred; when the ticker was disposed before the next tick. + public ValueTask WaitForNextTickAsync(CancellationToken cancellationToken) + { + return _periodicTimer.WaitForNextTickAsync(cancellationToken); + } + + /// + /// Disposes the periodic timer owned by the ticker. + /// + public void Dispose() + { + _periodicTimer.Dispose(); + } +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobRuntimeRegistry.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobRuntimeRegistry.cs new file mode 100644 index 00000000..5f2b5eeb --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobRuntimeRegistry.cs @@ -0,0 +1,152 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using System.Collections.Concurrent; +using System.Threading; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Execution; + +/// +/// Registry that holds the live runtime state of the scheduled jobs. +/// +public sealed class ScheduledJobRuntimeRegistry : IScheduledJobRuntimeRegistry +{ + /// + /// Class that holds the live runtime state of the execution cycle of a scheduled job. + /// + private sealed class ScheduledJobRuntimeState + { + /// + /// Object used to synchronize the access to the runtime state of the scheduled job. + /// + public readonly object SyncRoot = new(); + + /// + /// Gets or sets the cancellation token source of the running execution cycle, or when no cycle is running. + /// + public CancellationTokenSource? CycleCancellationTokenSource; + + /// + /// Gets the slot that guards a scheduled job against overlapping executions. + /// + public readonly SemaphoreSlim RunSlot = new(1, 1); + } + + // One runtime state instance exists per scheduled job, and it is shared by every thread that works on that job: the + // cycle worker of the job, the request handlers that stop or remove the job, and the one time (fired) executions. The + // ConcurrentDictionary only makes the lookup of the state instance itself thread safe; the fields of the instance are + // still plain mutable fields, so every read or write of them is guarded by the per-state lock. The lock is only ever + // held for the few instructions that mutate or read the state, never while a cancellation callback runs, and the lock + // is reentrant for the thread that owns it, which keeps the registry free of deadlocks. + private readonly ConcurrentDictionary _runtimeStates = []; + + /// + /// Starts the execution cycle of the scheduled job identified by . + /// + /// The object representing the unique identifier of the scheduled job whose cycle is started. + /// The cancellation token source used to stop the execution cycle. + /// when the cycle was started, when a cycle was already running. + public bool TryStartCycle(ScheduledJobId scheduledJobId, CancellationTokenSource cycleCancellationTokenSource) + { + ScheduledJobRuntimeState state = _runtimeStates.GetOrAdd(scheduledJobId, static _ => new ScheduledJobRuntimeState()); + lock (state.SyncRoot) + { + // The check and the assignment must be one atomic step: without the lock, two concurrent starts of the same job could both observe that + // no cycle is running and both store their own cancellation token source, so a job would end up with two live cycles at once. + // The lock serializes the starts, so exactly one wins. + if (state.CycleCancellationTokenSource is not null) + return false; + state.CycleCancellationTokenSource = cycleCancellationTokenSource; + return true; + } + } + + /// + /// Gets a value indicating whether the execution cycle of the scheduled job identified by is currently running. + /// + /// The object representing the unique identifier of the scheduled job whose cycle is checked. + /// when a cycle is currently running, otherwise. + public bool HasActiveCycle(ScheduledJobId scheduledJobId) + { + if (!_runtimeStates.TryGetValue(scheduledJobId, out ScheduledJobRuntimeState? state)) + return false; + // The read takes the same lock the writers use, so it never observes a partially updated state, and the lock also acts as the memory barrier + // that guarantees the read sees the latest value written by another thread. + lock (state.SyncRoot) + return state.CycleCancellationTokenSource is not null; + } + + /// + /// Stops the execution cycle of the scheduled job identified by . + /// + /// The object representing the unique identifier of the scheduled job whose cycle is stopped. + public void StopCycle(ScheduledJobId scheduledJobId) + { + if (!_runtimeStates.TryGetValue(scheduledJobId, out ScheduledJobRuntimeState? state)) + return; + CancellationTokenSource? cycleCancellationTokenSource; + lock (state.SyncRoot) + { + // The stored token source is read and cleared while the lock is held, so that a start that races with this stop either sees the cycle and loses, + // or sees no cycle and starts a fresh one whose token source is not the one cancelled here. + cycleCancellationTokenSource = state.CycleCancellationTokenSource; + state.CycleCancellationTokenSource = null; + } + // Cancelling a token source synchronously invokes every callback registered on its token, and those callbacks can reach back into this registry + // (for example the cycle worker that unwinds and ends its own cycle). The lock is therefore released before the cancellation runs, + // so no callback ever executes while the lock is held, and the lock is never held longer than the few instructions that mutate the state. + cycleCancellationTokenSource?.Cancel(); + } + + /// + /// Ends the execution cycle of the scheduled job identified by , when it was started with . + /// + /// The object representing the unique identifier of the scheduled job whose cycle is ended. + /// The cancellation token source of the cycle that is ending. + /// + /// The cycle worker calls this method when its cycle finishes, so that a cycle that was replaced by a newer one + /// after being stopped can never cancel the cycle that replaced it. + /// + public void EndCycle(ScheduledJobId scheduledJobId, CancellationTokenSource cycleCancellationTokenSource) + { + if (_runtimeStates.TryGetValue(scheduledJobId, out ScheduledJobRuntimeState? state)) + lock (state.SyncRoot) + // The identity check matters for the stop-then-start race: when a worker is stopped and a newer cycle is started before the old worker reaches + // its cleanup, the stored token source already belongs to the new cycle. The old worker must only clear the field when it still owns it, + // so it can never cancel the cycle that replaced it. + if (ReferenceEquals(state.CycleCancellationTokenSource, cycleCancellationTokenSource)) + state.CycleCancellationTokenSource = null; + // Cancelling the worker's own token source is always safe and idempotent, and runs outside the lock for the same reason as in StopCycle: + // the cancellation callbacks must not execute while the lock is held. + cycleCancellationTokenSource.Cancel(); + } + + /// + /// Attempts to reserve the execution slot of the scheduled job identified by . + /// + /// The object representing the unique identifier of the scheduled job whose execution slot is reserved. + /// when the slot was reserved, when another execution is already running. + public bool TryAcquireRunSlot(ScheduledJobId scheduledJobId) + { + ScheduledJobRuntimeState state = _runtimeStates.GetOrAdd(scheduledJobId, static _ => new ScheduledJobRuntimeState()); + lock (state.SyncRoot) + // The slot is acquired under the same lock that guards the rest of the state, so the acquire is serialized + // with the cycle start and end transitions of the job; Wait(0) never blocks, so the lock is held only for a single non blocking instruction. + return state.RunSlot.Wait(0); + } + + /// + /// Releases the execution slot of the scheduled job identified by . + /// + /// The object representing the unique identifier of the scheduled job whose execution slot is released. + public void ReleaseRunSlot(ScheduledJobId scheduledJobId) + { + if (!_runtimeStates.TryGetValue(scheduledJobId, out ScheduledJobRuntimeState? state)) + return; + lock (state.SyncRoot) + // The semaphore is only released when a slot is actually taken, which is checked under the same lock as the acquire; + // without that check, releasing a slot that was never acquired, or releasing it twice, would throw a SemaphoreFullException. + if (state.RunSlot.CurrentCount is 0) + state.RunSlot.Release(); + } +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs new file mode 100644 index 00000000..15511ac3 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs @@ -0,0 +1,544 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Scheduling; +using Lumina.Application.Common.Infrastructure.Themes; +using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using Lumina.Infrastructure.Core.Themes; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Execution; + +/// +/// Background service that schedules and executes the tasks of the scheduled jobs. +/// +public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobScheduler +{ + private readonly IServiceScopeFactory _serviceScopeFactory; + private readonly IScheduledJobRuntimeRegistry _runtimeRegistry; + private readonly ILogger _logger; + private readonly Func _cycleTickerFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected registry that holds the live runtime state of the scheduled jobs. + /// Injected service for logging. + /// Injected factory used for creating scopes in which services are requested. + public ScheduledJobSchedulerJob(IScheduledJobRuntimeRegistry runtimeRegistry, ILogger logger, IServiceScopeFactory serviceScopeFactory) + : this(runtimeRegistry, logger, serviceScopeFactory, period => new PeriodicScheduledJobCycleTicker(period)) + { + } + + /// + /// Initializes a new instance of the class with a custom cycle ticker factory. + /// + /// Injected registry that holds the live runtime state of the scheduled jobs. + /// Injected service for logging. + /// Injected factory used for creating scopes in which services are requested. + /// Factory that creates the ticker driving the cadence of an execution cycle, for which the unit tests substitute a stubbed ticker. + internal ScheduledJobSchedulerJob(IScheduledJobRuntimeRegistry runtimeRegistry, ILogger logger, IServiceScopeFactory serviceScopeFactory, Func cycleTickerFactory) + { + _serviceScopeFactory = serviceScopeFactory; + _runtimeRegistry = runtimeRegistry; + _logger = logger; + _cycleTickerFactory = cycleTickerFactory; + } + + /// + /// Starts the execution cycle of the scheduled job identified by . + /// + /// The object representing the unique identifier of the scheduled job whose execution cycle is started. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + public Task StartCycleAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken) + { + RunCycleWorkerAsync(scheduledJobId, runImmediately: true, cancellationToken).FireAndForgetSafeAsync(); + return Task.CompletedTask; + } + + /// + /// Stops the execution cycle of the scheduled job identified by . + /// + /// The object representing the unique identifier of the scheduled job whose execution cycle is stopped. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + public Task StopCycleAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken) + { + _runtimeRegistry.StopCycle(scheduledJobId); + return Task.CompletedTask; + } + + /// + /// Fires the task of the scheduled job identified by once, without affecting its execution cycle. + /// + /// The object representing the unique identifier of the scheduled job whose task is fired. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + public Task RunOnceAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken) + { + RunOnceWorkerAsync(scheduledJobId, cancellationToken).FireAndForgetSafeAsync(); + return Task.CompletedTask; + } + + /// + /// Method called when the background service starts; resumes the execution cycles of the scheduled jobs whose cycle was active. + /// + /// Cancellation token that can be used to stop the execution. + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + await SynchronizeBundledThemesIfNeededAsync(stoppingToken).ConfigureAwait(false); + await ResumeActiveCyclesAsync(stoppingToken).ConfigureAwait(false); + try + { + await Task.Delay(Timeout.InfiniteTimeSpan, stoppingToken).ConfigureAwait(false); + } + catch (OperationCanceledException) { } + } + + /// + /// Installs and repairs the bundled themes at startup, but only when no active "Repair themes at startup" scheduled job will do it. + /// + /// Cancellation token that can be used to stop the execution. + /// + /// The default "Repair themes at startup" job is the single owner of the theme synchronization once the default jobs are + /// seeded during the application setup. Until then, for example on a fresh installation before the administrator account is + /// created, no scheduled job exists yet, so the themes are synchronized here, otherwise the pages of the setup flow would + /// have no theme to render and a hosted test host would have no bundled themes installed. + /// + private async Task SynchronizeBundledThemesIfNeededAsync(CancellationToken cancellationToken) + { + try + { + await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = scope.ServiceProvider.GetRequiredService(); + Result> getScheduledJobsResult = await unitOfWork.ScheduledJobRepository.GetActiveOrRunningAsync(cancellationToken).ConfigureAwait(false); + if (getScheduledJobsResult.IsFailure) + { + _logger.LogWarning("Failed to read the scheduled jobs to decide whether the themes must be synchronized: {Error}", getScheduledJobsResult.FirstError.Description); + return; + } + // When an active "Repair themes at startup" job exists, its cycle is resumed below and it runs the synchronization. + if (getScheduledJobsResult.Value.Any(scheduledJob => scheduledJob.TaskType == ScheduledTaskType.RepairThemes)) + return; + + IThemeService themeService = scope.ServiceProvider.GetRequiredService(); + await ThemeSynchronizer.SynchronizeAsync(themeService, unitOfWork, _logger, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) { } + catch (Exception exception) + { + // Synchronizing the themes at startup is best effort, so a failure here must never stop the scheduler. + _logger.LogWarning(exception, "Failed to synchronize the bundled themes at startup."); + } + } + + /// + /// Resumes the execution cycles of the scheduled jobs whose cycle was active when the application shut down. + /// + /// Cancellation token that can be used to stop the execution. + private async Task ResumeActiveCyclesAsync(CancellationToken cancellationToken) + { + await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = scope.ServiceProvider.GetRequiredService(); + Result> getScheduledJobsResult = await unitOfWork.ScheduledJobRepository.GetActiveOrRunningAsync(cancellationToken).ConfigureAwait(false); + if (getScheduledJobsResult.IsFailure) + { + _logger.LogWarning("Failed to read the scheduled jobs to resume: {Error}", getScheduledJobsResult.FirstError.Description); + return; + } + foreach (ScheduledJobEntity scheduledJob in getScheduledJobsResult.Value) + { + ScheduledJobId scheduledJobId = ScheduledJobId.Create(scheduledJob.Id); + // A scheduled job that was running when the application shut down had its execution interrupted, so its open + // execution history row is closed and its status is reset before its cycle is resumed. + if (scheduledJob.Status == ScheduledJobStatus.Running) + { + ScheduledJobStatus reconciledStatus = await ReconcileInterruptedRunAsync(scheduledJobId, cancellationToken).ConfigureAwait(false); + if (reconciledStatus != ScheduledJobStatus.Active) + continue; + } + // A once at startup scheduled job fires immediately when its cycle is resumed at startup; the other scheduled jobs wait for their next scheduled execution. + bool runImmediately = scheduledJob.ScheduleType == ScheduleType.OnceAtStartup; + RunCycleWorkerAsync(scheduledJobId, runImmediately, cancellationToken).FireAndForgetSafeAsync(); + } + } + + /// + /// Runs the execution cycle worker of the scheduled job identified by . + /// + /// The object representing the unique identifier of the scheduled job whose cycle is run. + /// Whether the task of the scheduled job is run immediately when the cycle starts. + /// Cancellation token that can be used to stop the execution. + private async Task RunCycleWorkerAsync(ScheduledJobId scheduledJobId, bool runImmediately, CancellationToken stoppingToken) + { + // Each cycle owns its own cancellation token source: it is the handle the runtime registry stores, so stopping one + // scheduled job cancels exactly this cycle and no other job's cycle, even though the cycle worker itself runs "fire and forget" on another thread. + using CancellationTokenSource cycleCancellationTokenSource = new(); + // A scheduled job has at most one live cycle, and starts are "fire and forget", so when the registry already holds a + // cycle for the job, there is nothing for this worker to do and the existing cycle keeps ticking. + if (!_runtimeRegistry.TryStartCycle(scheduledJobId, cycleCancellationTokenSource)) + return; + + try + { + // The cycle token is cancelled when the application shuts down (through the host stopping token) or when this cycle is stopped + // (through its own token source), so a single token lets every await of the cycle observe both stop paths. + using CancellationTokenSource linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken, cycleCancellationTokenSource.Token); + CancellationToken cycleToken = linkedCancellationTokenSource.Token; + // An immediate run is executed as a cycle run, so it completes the scheduled job back to its active state and is + // recorded as part of the cycle; this is the path taken by an admin start, by the resume at startup and by the seed of the default jobs. + if (runImmediately) + await RunScheduledJobAsync(scheduledJobId, isCycleRun: true, cycleToken).ConfigureAwait(false); + + // The schedule is read from the storage medium for every cycle, so the delay until the next run is always + // computed from the persisted schedule; when the scheduled job can no longer be read, the cycle simply ends. + Schedule? schedule = await GetScheduleAsync(scheduledJobId, cycleToken).ConfigureAwait(false); + if (schedule is null) + return; + // A once at startup schedule fires its task exactly once when its cycle starts, at the application startup; the cycle + // then ends, and the scheduled job stays active, so its cycle is started again at the next application startup. + if (schedule.ScheduleType == ScheduleType.OnceAtStartup) + return; + + TimeSpan delay = await CalculateDelayAsync(schedule).ConfigureAwait(false); + // The ticker owns the cadence of the cycle: an interval schedule ticks every interval, and a daily schedule ticks + // after the delay until the next daily hour and minute. The default ticker wraps a periodic timer, which does not + // queue missed ticks, so a run that outlasts its period drops the missed ticks instead of piling them up. + using IScheduledJobCycleTicker cycleTicker = _cycleTickerFactory(delay); + // Each iteration waits for the next tick, runs the task and loops; a cancelled token or a disposed ticker makes + // WaitForNextTickAsync exit, which ends the cycle through the finally block below. + while (await cycleTicker.WaitForNextTickAsync(cycleToken).ConfigureAwait(false)) + { + if (cycleToken.IsCancellationRequested) + return; + // The run is awaited inside the tick and missed ticks are not queued, so a task that outlasts its interval + // drops the missed ticks instead of piling them up; the run slot acquired inside RunScheduledJobAsync is the + // second guard against overlapping executions. + await RunScheduledJobAsync(scheduledJobId, isCycleRun: true, cycleToken).ConfigureAwait(false); + // A daily schedule needs its delay recalculated after every run from the current time, so the next run + // happens at the next day's hour and minute, also across daylight saving time changes. + if (schedule.ScheduleType == ScheduleType.DailyAtHourAndMinute) + cycleTicker.Period = await CalculateDelayAsync(schedule).ConfigureAwait(false); + } + } + catch (OperationCanceledException) + { + // A cancelled cycle is the normal way the loop ends when the cycle is stopped or the application shuts down, so it is not an error and must not be logged as one. + } + catch (Exception exception) + { + // Failures of a single run are handled inside RunScheduledJobAsync, so an exception reaching this point is unexpected and ends the cycle. + _logger.LogError(exception, "The execution cycle of the scheduled job '{ScheduledJobId}' failed.", scheduledJobId.Value); + } + finally + { + // The registry is always told that the cycle ended, because every exit path passes through here, including the + // early returns above; EndCycle cancels and deregisters the cycle, and the outer using disposes the token source. + _runtimeRegistry.EndCycle(scheduledJobId, cycleCancellationTokenSource); + } + } + + /// + /// Runs the task of the scheduled job identified by once. + /// + /// The object representing the unique identifier of the scheduled job whose task is run. + /// Cancellation token that can be used to stop the execution. + private async Task RunOnceWorkerAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken) + { + try + { + await RunScheduledJobAsync(scheduledJobId, isCycleRun: false, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) { } + catch (Exception exception) + { + _logger.LogError(exception, "The one time execution of the scheduled job '{ScheduledJobId}' failed.", scheduledJobId.Value); + } + } + + /// + /// Runs the task of the scheduled job identified by , guarding it against overlapping executions. + /// + /// The object representing the unique identifier of the scheduled job whose task is run. + /// Whether the execution was triggered by the execution cycle of the scheduled job, or it is a one time execution. + /// Cancellation token that can be used to stop the execution. + private async Task RunScheduledJobAsync(ScheduledJobId scheduledJobId, bool isCycleRun, CancellationToken cancellationToken) + { + // Skip the execution when another execution of the same scheduled job is already running. + if (!_runtimeRegistry.TryAcquireRunSlot(scheduledJobId)) + return; + try + { + await ExecuteScheduledJobRunAsync(scheduledJobId, isCycleRun, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + // An execution that was cancelled is a normal outcome when the cycle of the scheduled job is stopped or the application shuts down. + } + catch (Exception exception) + { + _logger.LogError(exception, "The execution of the scheduled job '{ScheduledJobId}' failed unexpectedly.", scheduledJobId.Value); + await ReconcileInterruptedRunAsync(scheduledJobId, CancellationToken.None).ConfigureAwait(false); + } + finally + { + _runtimeRegistry.ReleaseRunSlot(scheduledJobId); + } + } + + /// + /// Executes a single run of the task of the scheduled job identified by . + /// + /// The object representing the unique identifier of the scheduled job whose task is run. + /// Whether the execution was triggered by the execution cycle of the scheduled job, or it is a one time execution. + /// Cancellation token that can be used to stop the execution. + private async Task ExecuteScheduledJobRunAsync(ScheduledJobId scheduledJobId, bool isCycleRun, CancellationToken cancellationToken) + { + // A run that was requested to stop before it started must not start at all. + if (cancellationToken.IsCancellationRequested) + return; + + await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope(); + IServiceProvider services = scope.ServiceProvider; + IUnitOfWork unitOfWork = services.GetRequiredService(); + IDomainEventPublisher domainEventPublisher = services.GetRequiredService(); + + // Load the scheduled job, and mark its task as started. + Result getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken).ConfigureAwait(false); + if (getScheduledJobResult.IsFailure || getScheduledJobResult.Value is null) + return; + Result scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity(); + if (scheduledJobDomainResult.IsFailure) + return; + ScheduledJob scheduledJob = scheduledJobDomainResult.Value; + Result startExecutionResult = scheduledJob.MarkExecutionStarted(isCycleRun); + if (startExecutionResult.IsFailure) + return; + foreach (IDomainEvent domainEvent in scheduledJob.GetDomainEvents()) + await domainEventPublisher.PublishAsync(domainEvent, cancellationToken).ConfigureAwait(false); + + // Execute the payload of the task of the scheduled job; a payload failure is a normal outcome that is logged, while a + // thrown exception is logged as well, so that the run is still completed instead of leaving the scheduled job running. + try + { + if (cancellationToken.IsCancellationRequested) + return; + IScheduledTaskExecutorFactory taskExecutorFactory = services.GetRequiredService(); + IScheduledTaskExecutor taskExecutor = taskExecutorFactory.CreateExecutor(scheduledJob.TaskType); + Result executePayloadResult = await taskExecutor.ExecutePayloadAsync(scheduledJob, cancellationToken).ConfigureAwait(false); + if (executePayloadResult.IsFailure) + _logger.LogWarning("The task of the scheduled job '{ScheduledJobName}' failed: {Error}", scheduledJob.Name, executePayloadResult.FirstError.Description); + } + catch (OperationCanceledException) + { + return; + } + catch (Exception exception) + { + _logger.LogError(exception, "The task of the scheduled job '{ScheduledJobName}' threw an exception.", scheduledJob.Name); + } + + if (cancellationToken.IsCancellationRequested) + return; + + await CompleteExecutionAsync(scheduledJob, unitOfWork, domainEventPublisher, isCycleRun, cancellationToken).ConfigureAwait(false); + } + + /// + /// Completes the execution of the task of , when the scheduled job is still running. + /// + /// The scheduled job whose task execution is completed. + /// The unit of work of the current run, whose tracked entities are reused by the completion handlers. + /// The publisher used to publish the completion domain events. + /// Whether the execution was triggered by the execution cycle of the scheduled job, or it is a one time execution. + /// Cancellation token that can be used to stop the execution. + private async Task CompleteExecutionAsync(ScheduledJob scheduledJob, IUnitOfWork unitOfWork, IDomainEventPublisher domainEventPublisher, bool isCycleRun, CancellationToken cancellationToken) + { + try + { + // Reload the scheduled job from the storage medium without tracking, because a stop or a removal that happened while the + // task was executing already reset its state, and completing the execution here would silently undo that change. + Result getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdWithoutTrackingAsync(scheduledJob.Id.Value, cancellationToken).ConfigureAwait(false); + if (getScheduledJobResult.IsFailure || getScheduledJobResult.Value is null) + return; + if (getScheduledJobResult.Value.Status != ScheduledJobStatus.Running) + return; + + // A one time execution returns the scheduled job to its active state when its execution cycle is still running, so the + // running cycle keeps scheduling executions and the job can still be stopped; the same applies to a once at startup job, + // whose active state is what makes it fire again at the next application startup. + bool completesTheCycleRun = isCycleRun || _runtimeRegistry.HasActiveCycle(scheduledJob.Id) || scheduledJob.Schedule.ScheduleType == ScheduleType.OnceAtStartup; + Result completeExecutionResult = scheduledJob.MarkExecutionCompleted(completesTheCycleRun); + if (completeExecutionResult.IsFailure) + return; + foreach (IDomainEvent domainEvent in scheduledJob.GetDomainEvents()) + await domainEventPublisher.PublishAsync(domainEvent, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) { } + catch (Exception exception) + { + // The completion failed after the execution was persisted as running, so the interrupted run is reconciled directly. + _logger.LogError(exception, "Failed to complete the execution of the scheduled job '{ScheduledJobId}'.", scheduledJob.Id.Value); + await ReconcileInterruptedRunAsync(scheduledJob.Id, CancellationToken.None).ConfigureAwait(false); + } + } + + /// + /// Reconciles the scheduled job identified by when its execution was interrupted: its open + /// execution history row is closed, and the scheduled job is returned to a status from which it can run again. + /// + /// The object representing the unique identifier of the scheduled job whose interrupted execution is reconciled. + /// Cancellation token that can be used to stop the execution. + /// The status the scheduled job was reconciled to, or its current status when no reconciliation was needed. + private async Task ReconcileInterruptedRunAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken) + { + try + { + await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = scope.ServiceProvider.GetRequiredService(); + Result getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken).ConfigureAwait(false); + if (getScheduledJobResult.IsFailure || getScheduledJobResult.Value is null) + return ScheduledJobStatus.Added; + ScheduledJobEntity scheduledJob = getScheduledJobResult.Value; + // A scheduled job that is not running needs no reconciliation. + if (scheduledJob.Status != ScheduledJobStatus.Running) + return scheduledJob.Status; + + // An interrupted execution returns the scheduled job to its active state when its execution cycle was active + // when the execution started, so its cycle is resumed at startup; an interrupted execution of a job whose cycle + // was not active returns it to its added state. The cycle active state is read from the execution history row + // and not from the IsCycleRun flag, so that a manually fired one time execution on an active job keeps its + // manual audit trail while its cycle is still resumed. + Result getOpenExecutionResult = await unitOfWork.ScheduledJobExecutionRepository + .GetOpenByScheduledJobIdAsync(scheduledJob.Id, cancellationToken).ConfigureAwait(false); + if (getOpenExecutionResult.IsFailure) + return ScheduledJobStatus.Added; + ScheduledJobExecutionEntity? openExecution = getOpenExecutionResult.Value; + ScheduledJobStatus reconciledStatus = (openExecution?.WasCycleActive ?? true) ? ScheduledJobStatus.Active : ScheduledJobStatus.Added; + + Result updateScheduledJobResult = await unitOfWork.ScheduledJobRepository.UpdateAsync( + CreateUpdatedScheduledJob(scheduledJob, reconciledStatus, scheduledJob.LastStartedOnUtc, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + if (updateScheduledJobResult.IsFailure) + return ScheduledJobStatus.Added; + if (openExecution is not null) + { + Result updateExecutionResult = await unitOfWork.ScheduledJobExecutionRepository.UpdateAsync( + CreateClosedExecution(openExecution, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + if (updateExecutionResult.IsFailure) + return ScheduledJobStatus.Added; + } + await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + _logger.LogInformation("The interrupted execution of the scheduled job '{ScheduledJobName}' was closed.", scheduledJob.Name); + return reconciledStatus; + } + catch (OperationCanceledException) + { + return ScheduledJobStatus.Added; + } + catch (Exception exception) + { + _logger.LogWarning(exception, "Failed to reconcile the interrupted execution of the scheduled job '{ScheduledJobId}'.", scheduledJobId.Value); + return ScheduledJobStatus.Added; + } + } + + /// + /// Gets the schedule of the scheduled job identified by , or when it cannot be loaded. + /// + /// The object representing the unique identifier of the scheduled job whose schedule is retrieved. + /// Cancellation token that can be used to stop the execution. + /// The schedule of the scheduled job, or . + private async Task GetScheduleAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken) + { + await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = scope.ServiceProvider.GetRequiredService(); + Result getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken).ConfigureAwait(false); + if (getScheduledJobResult.IsFailure || getScheduledJobResult.Value is null) + return null; + Result scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity(); + return scheduledJobDomainResult.IsFailure ? null : scheduledJobDomainResult.Value.Schedule; + } + + /// + /// Calculates the delay until the next execution of the scheduled job, based on its . + /// + /// The schedule used to calculate the delay. + /// The calculated delay until the next execution of the scheduled job. + private async Task CalculateDelayAsync(Schedule schedule) + { + await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope(); + IDateTimeProvider dateTimeProvider = scope.ServiceProvider.GetRequiredService(); + // The daily hour and minute of a schedule are expressed in the local time of the server, so that a daily schedule follows the clock the server runs on. + return schedule.GetDelayUntilNextExecution(dateTimeProvider.UtcNow, TimeZoneInfo.Local); + } + + /// + /// Creates a copy of with the provided status and timestamps. + /// + /// The scheduled job to copy. + /// The status of the copy. + /// The last start time of the copy. + /// The last completion time of the copy. + /// The copy of the scheduled job. + private static ScheduledJobEntity CreateUpdatedScheduledJob(ScheduledJobEntity scheduledJob, ScheduledJobStatus status, DateTime? lastStartedOnUtc, DateTime? lastCompletedOnUtc) + { + return new ScheduledJobEntity + { + Id = scheduledJob.Id, + Name = scheduledJob.Name, + TaskType = scheduledJob.TaskType, + ScheduleType = scheduledJob.ScheduleType, + IntervalMinutes = scheduledJob.IntervalMinutes, + Hour = scheduledJob.Hour, + Minute = scheduledJob.Minute, + Status = status, + OwnerUserId = scheduledJob.OwnerUserId, + LastStartedOnUtc = lastStartedOnUtc, + LastCompletedOnUtc = lastCompletedOnUtc, + CreatedOnUtc = scheduledJob.CreatedOnUtc, + CreatedBy = scheduledJob.CreatedBy, + UpdatedOnUtc = scheduledJob.UpdatedOnUtc, + UpdatedBy = scheduledJob.UpdatedBy + }; + } + + /// + /// Creates a copy of with the provided completion time. + /// + /// The execution to copy. + /// The completion time of the copy. + /// The copy of the execution. + private static ScheduledJobExecutionEntity CreateClosedExecution(ScheduledJobExecutionEntity execution, DateTime? completedOnUtc) + { + return new ScheduledJobExecutionEntity + { + Id = execution.Id, + ScheduledJobId = execution.ScheduledJobId, + TaskType = execution.TaskType, + IsCycleRun = execution.IsCycleRun, + WasCycleActive = execution.WasCycleActive, + StartedOnUtc = execution.StartedOnUtc, + CompletedOnUtc = completedOnUtc, + CreatedOnUtc = execution.CreatedOnUtc, + CreatedBy = execution.CreatedBy, + UpdatedOnUtc = execution.UpdatedOnUtc, + UpdatedBy = execution.UpdatedBy + }; + } +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledTaskExecutorFactory.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledTaskExecutorFactory.cs new file mode 100644 index 00000000..ce493bfb --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledTaskExecutorFactory.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors; +using Microsoft.Extensions.DependencyInjection; +using System; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Execution; + +/// +/// Factory that creates the executor of the task of a scheduled job, based on the type of its task. +/// +public class ScheduledTaskExecutorFactory : IScheduledTaskExecutorFactory +{ + private readonly IServiceProvider _serviceProvider; + + /// + /// Initializes a new instance of the class. + /// + /// The service provider. + public ScheduledTaskExecutorFactory(IServiceProvider serviceProvider) + { + _serviceProvider = serviceProvider; + } + + /// + /// Creates the executor of the task of a scheduled job, based on the type of its task. + /// + /// The type of the task whose executor is created. + /// The created task executor. + public IScheduledTaskExecutor CreateExecutor(ScheduledTaskType taskType) + { + return taskType switch + { + ScheduledTaskType.ScanMediaLibraries => _serviceProvider.GetRequiredService(), + ScheduledTaskType.CleanTemporaryFiles => _serviceProvider.GetRequiredService(), + ScheduledTaskType.RepairThemes => _serviceProvider.GetRequiredService(), + ScheduledTaskType.CleanScheduledJobExecutionHistory => _serviceProvider.GetRequiredService(), + _ => throw new ArgumentException($"Unsupported task type: {taskType}", nameof(taskType)) + }; + } +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/CleanScheduledJobExecutionHistoryTaskExecutor.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/CleanScheduledJobExecutionHistoryTaskExecutor.cs new file mode 100644 index 00000000..b0aac116 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/CleanScheduledJobExecutionHistoryTaskExecutor.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Microsoft.Extensions.Logging; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors; + +/// +/// Task executor that cleans the execution history of the scheduled jobs, keeping only the executions of the past month. +/// +public class CleanScheduledJobExecutionHistoryTaskExecutor : IScheduledTaskExecutor +{ + private readonly IDateTimeProvider _dateTimeProvider; + private readonly IUnitOfWork _unitOfWork; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for time related concerns. + /// Injected service for logging. + /// Injected unit of work for interacting with the data access layer repositories. + public CleanScheduledJobExecutionHistoryTaskExecutor(IDateTimeProvider dateTimeProvider, ILogger logger, IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + _dateTimeProvider = dateTimeProvider; + _logger = logger; + } + + /// + /// Removes the executions of the tasks of the scheduled jobs that are older than a month, keeping only the recent executions for audit. + /// + /// The scheduled job whose task is executed. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> ExecutePayloadAsync(ScheduledJob scheduledJob, CancellationToken cancellationToken) + { + DateTime cutoffUtc = _dateTimeProvider.UtcNow.AddMonths(-1); + Result deleteResult = await _unitOfWork.ScheduledJobExecutionRepository.DeleteOlderThanAsync(cutoffUtc, cancellationToken).ConfigureAwait(false); + if (deleteResult.IsFailure) + return deleteResult.Errors; + + _logger.LogInformation("Cleaned the execution history of the scheduled jobs on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name); + return Result.Success; + } +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutor.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutor.cs new file mode 100644 index 00000000..ed8bfaaf --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutor.cs @@ -0,0 +1,110 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors; + +/// +/// Task executor that scans all the enabled media libraries, on behalf of the owner of the scheduled job. +/// +public class MediaLibraryScanTaskExecutor : IScheduledTaskExecutor +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IDomainEventPublisher _domainEventPublisher; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The domain event publisher used to publish events. + /// Injected service for logging. + /// Injected unit of work for interacting with the data access layer repositories. + public MediaLibraryScanTaskExecutor(IDomainEventPublisher domainEventPublisher, ILogger logger, IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + _domainEventPublisher = domainEventPublisher; + _logger = logger; + } + + /// + /// Scans all the enabled media libraries, on behalf of the owner of the scheduled job. + /// + /// The scheduled job whose task is executed. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> ExecutePayloadAsync(ScheduledJob scheduledJob, CancellationToken cancellationToken) + { + Guid ownerUserId = scheduledJob.OwnerUserId.Value; + + // Get all the enabled and unlocked media libraries. + Result> getLibrariesResult = await _unitOfWork.LibraryRepository.GetAllEnabledAndUnlockedAsync(cancellationToken).ConfigureAwait(false); + if (getLibrariesResult.IsFailure) + return getLibrariesResult.Errors; + + IEnumerable> domainLibrariesResult = getLibrariesResult.Value.ToDomainEntities(); + List domainEvents = []; + + // Start a scan for each media library that is not already being scanned. + foreach (Result domainLibraryResult in domainLibrariesResult) + { + if (domainLibraryResult.IsFailure) + return domainLibraryResult.Errors; + + // Get the past month's scans for this library. + Result> pastLibraryScansResult = await _unitOfWork.LibraryScanRepository + .GetPastMonthScansByLibraryIdAsync(domainLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); + if (pastLibraryScansResult.IsFailure) + return pastLibraryScansResult.Errors; + + // Convert the repository scans history to domain objects. + IEnumerable> pastLibraryScansDomainResult = pastLibraryScansResult.Value.ToDomainEntities(); + foreach (Result pastLibraryScanDomainResult in pastLibraryScansDomainResult) + if (pastLibraryScanDomainResult.IsFailure) + return pastLibraryScanDomainResult.Errors; + + // Create and queue the media library scan. + Result libraryScanResult = LibraryScan.Create( + LibraryId.Create(domainLibraryResult.Value.Id.Value), + UserId.Create(ownerUserId), + [.. pastLibraryScansDomainResult.Select(pastLibraryScanDomainResult => pastLibraryScanDomainResult.Value)] + ); + if (libraryScanResult.IsFailure) + return libraryScanResult.Errors; + // A media library that is already being scanned is simply skipped, so the other libraries are still scanned. + if (libraryScanResult.Value.QueueScan().IsFailure) + continue; + + Result insertLibraryScanResult = await _unitOfWork.LibraryScanRepository.InsertAsync( + libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (insertLibraryScanResult.IsFailure) + return insertLibraryScanResult.Errors; + + domainEvents.AddRange(libraryScanResult.Value.GetDomainEvents()); + } + + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + // Publish the domain events of the queued media library scans. + foreach (IDomainEvent domainEvent in domainEvents) + await _domainEventPublisher.PublishAsync(domainEvent, cancellationToken).ConfigureAwait(false); + + _logger.LogInformation("Scanned all enabled media libraries on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name); + return Result.Success; + } +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/RepairThemesTaskExecutor.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/RepairThemesTaskExecutor.cs new file mode 100644 index 00000000..b9bbf77e --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/RepairThemesTaskExecutor.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Themes; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Infrastructure.Core.Themes; +using Microsoft.Extensions.Logging; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors; + +/// +/// Task executor that repairs the installed themes whose files are missing. +/// +public class RepairThemesTaskExecutor : IScheduledTaskExecutor +{ + private readonly IThemeService _themeService; + private readonly IUnitOfWork _unitOfWork; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for the server-side storage and serving of theme packs. + /// Injected service for logging. + /// Injected unit of work for interacting with the data access layer repositories. + public RepairThemesTaskExecutor(IThemeService themeService, ILogger logger, IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + _themeService = themeService; + _logger = logger; + } + + /// + /// Repairs the installed themes whose files are missing, reinstalling the files of the bundled themes from their shipped archives. + /// + /// The scheduled job whose task is executed. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> ExecutePayloadAsync(ScheduledJob scheduledJob, CancellationToken cancellationToken) + { + // Repairs are best effort, so a failure to repair one theme is logged inside the synchronizer and the remaining themes are still repaired. + try + { + await ThemeSynchronizer.SynchronizeAsync(_themeService, _unitOfWork, _logger, cancellationToken).ConfigureAwait(false); + _logger.LogInformation("Repaired the themes on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name); + return Result.Success; + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception exception) + { + _logger.LogWarning(exception, "The themes could not be repaired on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name); + return Error.Failure(description: nameof(RepairThemesTaskExecutor)); + } + } +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/TemporaryFilesCleanupTaskExecutor.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/TemporaryFilesCleanupTaskExecutor.cs new file mode 100644 index 00000000..8caabe91 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/TemporaryFilesCleanupTaskExecutor.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Microsoft.Extensions.Logging; +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors; + +/// +/// Task executor that empties the temporary directory into which the reading plugins extract the contents of the books. +/// +public class TemporaryFilesCleanupTaskExecutor : IScheduledTaskExecutor +{ + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for logging. + public TemporaryFilesCleanupTaskExecutor(ILogger logger) + { + _logger = logger; + } + + /// + /// Empties the temporary directory into which the reading plugins extract the contents of the books. + /// + /// The scheduled job whose task is executed. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> ExecutePayloadAsync(ScheduledJob scheduledJob, CancellationToken cancellationToken) + { + string temporaryDirectoryRoot = Path.GetFullPath(ReadingCachePaths.GetRootDirectory()); + string applicationBaseDirectory = Path.GetFullPath(AppContext.BaseDirectory); + StringComparison comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + + // Fail closed when the temporary directory could not be resolved inside the application base directory, so that a misconfiguration can never delete arbitrary directories. + if (string.IsNullOrWhiteSpace(temporaryDirectoryRoot) || + string.Equals(temporaryDirectoryRoot, Path.GetPathRoot(temporaryDirectoryRoot), comparison) || + !temporaryDirectoryRoot.StartsWith(applicationBaseDirectory, comparison) || + string.Equals(temporaryDirectoryRoot, applicationBaseDirectory, comparison)) + { + _logger.LogWarning("The temporary directory to clean could not be resolved safely, so the scheduled job '{ScheduledJobName}' was skipped.", scheduledJob.Name); + return Result.Success; + } + + try + { + if (Directory.Exists(temporaryDirectoryRoot)) + Directory.Delete(temporaryDirectoryRoot, recursive: true); + Directory.CreateDirectory(temporaryDirectoryRoot); + _logger.LogInformation("Emptied the temporary directory '{TemporaryDirectory}'.", temporaryDirectoryRoot); + return Result.Success; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + _logger.LogWarning(exception, "The temporary directory '{TemporaryDirectory}' could not be emptied.", temporaryDirectoryRoot); + return await Task.FromResult(Error.Failure(description: nameof(TemporaryFilesCleanupTaskExecutor))); + } + } +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Notifications/IScheduledJobsClient.cs b/src/Lumina.Infrastructure/Core/Scheduling/Notifications/IScheduledJobsClient.cs new file mode 100644 index 00000000..74885209 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Notifications/IScheduledJobsClient.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.Scheduling; +using System.Collections.Generic; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Notifications; + +/// +/// Interface for the SignalR client of the scheduled jobs hub. +/// +public interface IScheduledJobsClient +{ + /// + /// Receives the current list of scheduled jobs. + /// + /// The current list of scheduled jobs. + /// A task that represents the asynchronous operation. + Task ReceiveScheduledJobsAsync(IReadOnlyList scheduledJobs); + + /// + /// Receives an execution of the task of a scheduled job that started. + /// + /// The execution that started. + /// A task that represents the asynchronous operation. + Task ScheduledJobExecutionStartedAsync(ScheduledJobExecutionResponse execution); + + /// + /// Receives an execution of the task of a scheduled job that completed. + /// + /// The execution that completed. + /// A task that represents the asynchronous operation. + Task ScheduledJobExecutionCompletedAsync(ScheduledJobExecutionResponse execution); +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Notifications/ScheduledJobNotifier.cs b/src/Lumina.Infrastructure/Core/Scheduling/Notifications/ScheduledJobNotifier.cs new file mode 100644 index 00000000..94885e5b --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Notifications/ScheduledJobNotifier.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Scheduling.Notifications; +using Lumina.Contracts.Responses.Scheduling; +using Microsoft.AspNetCore.SignalR; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Notifications; + +/// +/// Class used to notify SignalR clients about the scheduled jobs and their executions. +/// +public sealed class ScheduledJobNotifier : IScheduledJobNotifier +{ + private readonly IHubContext _hubContext; + + /// + /// Initializes a new instance of the class. + /// + /// SignalR hub context abstraction. + public ScheduledJobNotifier(IHubContext hubContext) + { + _hubContext = hubContext; + } + + /// + /// Notifies the SignalR clients about the current list of scheduled jobs. + /// + /// The current list of scheduled jobs. + /// Cancellation token that can be used to stop the execution. + public async Task SendScheduledJobsAsync(IReadOnlyList scheduledJobs, CancellationToken cancellationToken) + { + await _hubContext.Clients.Group(ScheduledJobsHub.ADMINISTRATORS_GROUP).ReceiveScheduledJobsAsync(scheduledJobs).ConfigureAwait(false); + } + + /// + /// Notifies the SignalR clients about an execution of the task of a scheduled job that started. + /// + /// The execution of the task of the scheduled job that started. + /// Cancellation token that can be used to stop the execution. + public async Task SendScheduledJobExecutionStartedAsync(ScheduledJobExecutionResponse execution, CancellationToken cancellationToken) + { + await _hubContext.Clients.Group(ScheduledJobsHub.ADMINISTRATORS_GROUP).ScheduledJobExecutionStartedAsync(execution).ConfigureAwait(false); + } + + /// + /// Notifies the SignalR clients about an execution of the task of a scheduled job that completed. + /// + /// The execution of the task of the scheduled job that completed. + /// Cancellation token that can be used to stop the execution. + public async Task SendScheduledJobExecutionCompletedAsync(ScheduledJobExecutionResponse execution, CancellationToken cancellationToken) + { + await _hubContext.Clients.Group(ScheduledJobsHub.ADMINISTRATORS_GROUP).ScheduledJobExecutionCompletedAsync(execution).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Notifications/ScheduledJobsHub.cs b/src/Lumina.Infrastructure/Core/Scheduling/Notifications/ScheduledJobsHub.cs new file mode 100644 index 00000000..5d498ecb --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Notifications/ScheduledJobsHub.cs @@ -0,0 +1,65 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.SignalR; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using ApplicationAuthorizationService = Lumina.Application.Common.Infrastructure.Authorization.IAuthorizationService; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Notifications; + +/// +/// SignalR hub for broadcasting the state of the scheduled jobs to the connected administrator clients. +/// +[Authorize] +public class ScheduledJobsHub : Hub +{ + /// + /// Name of the group that holds the connections of the verified administrator clients. + /// + public const string ADMINISTRATORS_GROUP = "Administrators"; + + private readonly IServiceScopeFactory _serviceScopeFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected factory used for creating scopes in which services are requested. + public ScheduledJobsHub(IServiceScopeFactory serviceScopeFactory) + { + _serviceScopeFactory = serviceScopeFactory; + } + + /// + /// Verifies that the connecting client belongs to an administrator account, and rejects the connection otherwise. + /// + /// A task that represents the asynchronous operation. + public override async Task OnConnectedAsync() + { + string? userIdClaim = Context.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value; + if (!Guid.TryParse(userIdClaim, out Guid userId) || !await IsAdministratorAsync(userId).ConfigureAwait(false)) + { + Context.Abort(); + return; + } + // The connection is added to the administrator group only after the role check succeeded, so the notifications, which are + // broadcast to that group, can never reach a client whose connection was not verified to belong to an administrator. + await Groups.AddToGroupAsync(Context.ConnectionId, ADMINISTRATORS_GROUP).ConfigureAwait(false); + await base.OnConnectedAsync().ConfigureAwait(false); + } + + /// + /// Determines whether the user identified by is an administrator. + /// + /// The unique identifier of the user to check. + /// when the user is an administrator, otherwise. + private async Task IsAdministratorAsync(Guid userId) + { + await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope(); + ApplicationAuthorizationService authorizationService = scope.ServiceProvider.GetRequiredService(); + return await authorizationService.IsInRoleAsync(userId, "Admin", CancellationToken.None).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeSynchronizer.cs similarity index 51% rename from src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs rename to src/Lumina.Infrastructure/Core/Themes/ThemeSynchronizer.cs index 272832ec..7a0e94b4 100644 --- a/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeSynchronizer.cs @@ -5,8 +5,6 @@ using Lumina.Application.Common.Infrastructure.Models.DTO.Themes; using Lumina.Application.Common.Infrastructure.Themes; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Themes; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -19,76 +17,58 @@ using System.Threading.Tasks; namespace Lumina.Infrastructure.Core.Themes; /// -/// Background job that installs the bundled themes into the storage medium and the theme storage at startup. +/// Utility class that keeps the installed themes in sync with the bundled theme archives. /// -internal sealed class ThemeDetectionSyncJob : BackgroundService +internal static class ThemeSynchronizer { - private readonly IServiceScopeFactory _serviceScopeFactory; - private readonly IThemeService _themeService; - private readonly ILogger _logger; - /// - /// Initializes a new instance of the class. + /// Installs the bundled themes into the storage medium and the theme storage, and repairs the installed themes whose files are missing. /// - /// Injected factory for creating scopes in which services are requested. /// Injected service for the server-side storage and serving of theme packs. + /// The unit of work for interacting with the theme repository. /// Injected logger used for logging. - public ThemeDetectionSyncJob(IServiceScopeFactory serviceScopeFactory, IThemeService themeService, ILogger logger) - { - _serviceScopeFactory = serviceScopeFactory; - _themeService = themeService; - _logger = logger; - } - - /// - /// Method called when the background service starts. - /// /// Cancellation token that can be used to stop the execution. - protected override async Task ExecuteAsync(CancellationToken cancellationToken) + internal static async Task SynchronizeAsync(IThemeService themeService, IUnitOfWork unitOfWork, ILogger logger, CancellationToken cancellationToken) { - await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); - IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetRequiredService(); - - Result> getThemesResult = await unitOfWork.ThemeRepository.GetAllAsync(cancellationToken); + Result> getThemesResult = await unitOfWork.ThemeRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); if (getThemesResult.IsFailure) { - _logger.LogWarning("Failed to read the installed themes: {Error}", getThemesResult.FirstError.Description); + logger.LogWarning("Failed to read the installed themes: {Error}", getThemesResult.FirstError.Description); return; } - // themes that were soft deleted by the user must not be reinstalled automatically + // Themes that were soft deleted by the user must not be reinstalled automatically. List themes = [.. getThemesResult.Value]; - foreach (string archivePath in _themeService.GetBundledThemeArchivePaths()) + foreach (string archivePath in themeService.GetBundledThemeArchivePaths()) { - Result manifestResult = await _themeService.ReadManifestFromArchiveAsync(archivePath, cancellationToken); + Result manifestResult = await themeService.ReadManifestFromArchiveAsync(archivePath, cancellationToken).ConfigureAwait(false); if (manifestResult.IsFailure) { - _logger.LogWarning("Skipping bundled theme archive {ArchivePath}: {Error}", archivePath, manifestResult.FirstError.Description); + logger.LogWarning("Skipping bundled theme archive {ArchivePath}: {Error}", archivePath, manifestResult.FirstError.Description); continue; } ThemeEntity? existingTheme = themes.Where(theme => theme.ThemeId == manifestResult.Value.Id).FirstOrDefault(); - // a theme that was soft deleted by the user must not be reinstalled automatically; an installed bundled theme - // whose files are present is already in sync, so only a bundled theme whose files went missing gets its files reinstalled - if (existingTheme is not null && (existingTheme.IsDeleted || existingTheme.InstallSource != ThemeInstallSource.Bundled || _themeService.HasThemePack(existingTheme.ThemeId))) + // A theme that was soft deleted by the user must not be reinstalled automatically; an installed bundled theme + // whose files are present is already in sync, so only a bundled theme whose files went missing gets its files reinstalled. + if (existingTheme is not null && (existingTheme.IsDeleted || existingTheme.InstallSource != ThemeInstallSource.Bundled || themeService.HasThemePack(existingTheme.ThemeId))) continue; - // installing a bundled theme at startup is best effort: a file system failure here must never crash the host, - // because the default BackgroundServiceExceptionBehavior (StopHost) shuts down the whole application and - // disposes its service provider, making every later request fail + // Installing a bundled theme at startup is best effort: a file system failure here must never crash the host, because the default + // BackgroundServiceExceptionBehavior (StopHost) shuts down the whole application and disposes its service provider, making every later request fail. try { await using FileStream archive = File.OpenRead(archivePath); - Result installResult = await _themeService.InstallAsync(archive, cancellationToken); + Result installResult = await themeService.InstallAsync(archive, cancellationToken).ConfigureAwait(false); if (installResult.IsFailure) { - _logger.LogWarning("Failed to install bundled theme '{ThemeId}': {Error}", manifestResult.Value.Id, installResult.FirstError.Description); + logger.LogWarning("Failed to install bundled theme '{ThemeId}': {Error}", manifestResult.Value.Id, installResult.FirstError.Description); continue; } - // a known theme only gets its missing files reinstalled, so no new row is inserted + // A known theme only gets its missing files reinstalled, so no new row is inserted. if (existingTheme is not null) continue; @@ -108,40 +88,41 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService UpdatedBy = default }; - Result insertResult = await unitOfWork.ThemeRepository.InsertAsync(themeEntity, cancellationToken); + Result insertResult = await unitOfWork.ThemeRepository.InsertAsync(themeEntity, cancellationToken).ConfigureAwait(false); if (insertResult.IsFailure) - _logger.LogWarning("Failed to persist the detection of theme '{ThemeId}': {Error}", manifestResult.Value.Id, insertResult.FirstError.Description); + logger.LogWarning("Failed to persist the detection of theme '{ThemeId}': {Error}", manifestResult.Value.Id, insertResult.FirstError.Description); else themes.Add(themeEntity); } catch (IOException exception) { - _logger.LogWarning(exception, "Failed to install bundled theme '{ThemeId}': the theme files could not be written.", manifestResult.Value.Id); + logger.LogWarning(exception, "Failed to install bundled theme '{ThemeId}': the theme files could not be written.", manifestResult.Value.Id); } catch (UnauthorizedAccessException exception) { - _logger.LogWarning(exception, "Failed to install bundled theme '{ThemeId}': access to the theme files was denied.", manifestResult.Value.Id); + logger.LogWarning(exception, "Failed to install bundled theme '{ThemeId}': access to the theme files was denied.", manifestResult.Value.Id); } } - await CleanUpMissingThemePacksAsync(unitOfWork, themes, cancellationToken); - await EnsureCurrentThemeExistsAsync(unitOfWork, themes, cancellationToken); + await CleanUpMissingThemePacksAsync(themeService, unitOfWork, themes, logger, cancellationToken).ConfigureAwait(false); + await EnsureCurrentThemeExistsAsync(themeService, unitOfWork, themes, cancellationToken).ConfigureAwait(false); - await unitOfWork.SaveChangesAsync(cancellationToken); + await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); } /// /// Restores the files of the damaged bundled themes that were not deleted by the user, and removes the damaged themes whose files could not be recovered. /// + /// Injected service for the server-side storage and serving of theme packs. /// The unit of work for interacting with the theme repository. /// The installed themes read from the storage medium. + /// Injected logger used for logging. /// Cancellation token that can be used to stop the execution. - private async Task CleanUpMissingThemePacksAsync(IUnitOfWork unitOfWork, IReadOnlyList themes, CancellationToken cancellationToken) + private static async Task CleanUpMissingThemePacksAsync(IThemeService themeService, IUnitOfWork unitOfWork, IReadOnlyList themes, ILogger logger, CancellationToken cancellationToken) { - // a soft deleted theme was deleted intentionally from the admin interface, so it must never be restored - // automatically; only a theme that was not deleted, but whose files went missing, was corrupted or removed - // externally, and is the only case where the files are restored - IReadOnlyList brokenThemes = [.. themes.Where(theme => !theme.IsDeleted && !_themeService.HasThemePack(theme.ThemeId))]; + // A soft deleted theme was deleted intentionally from the admin interface, so it must never be restored automatically; + // only a theme that was not deleted, but whose files went missing, was corrupted or removed externally, and is the only case where the files are restored. + IReadOnlyList brokenThemes = [.. themes.Where(theme => !theme.IsDeleted && !themeService.HasThemePack(theme.ThemeId))]; if (brokenThemes.Count is 0) return; @@ -151,39 +132,39 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService { if (brokenTheme.InstallSource == ThemeInstallSource.Bundled) { - // the files of a bundled theme that was not deleted by the user are restored from its shipped archive - Result restoreResult = await _themeService.RestoreBundledThemeAsync(brokenTheme.ThemeId, cancellationToken); + // The files of a bundled theme that was not deleted by the user are restored from its shipped archive. + Result restoreResult = await themeService.RestoreBundledThemeAsync(brokenTheme.ThemeId, cancellationToken).ConfigureAwait(false); if (restoreResult.IsSuccess) continue; - _logger.LogWarning("Failed to restore the files of bundled theme '{ThemeId}': {Error}", brokenTheme.ThemeId, restoreResult.FirstError.Description); + logger.LogWarning("Failed to restore the files of bundled theme '{ThemeId}': {Error}", brokenTheme.ThemeId, restoreResult.FirstError.Description); - // at least one bundled theme must always remain available, so the application never ends up without any theme; - // the last remaining bundled theme is kept even when its files cannot be recovered + // At least one bundled theme must always remain available, so the application never ends up without any theme; + // the last remaining bundled theme is kept even when its files cannot be recovered. int availableBundledThemes = themes.Count(availableTheme => !availableTheme.IsDeleted && availableTheme.InstallSource == ThemeInstallSource.Bundled); if (availableBundledThemes <= 1) { - _logger.LogWarning("Bundled theme '{ThemeId}' is the last remaining bundled theme and its files could not be restored, so it is kept.", brokenTheme.ThemeId); + logger.LogWarning("Bundled theme '{ThemeId}' is the last remaining bundled theme and its files could not be restored, so it is kept.", brokenTheme.ThemeId); continue; } - // a bundled theme whose files could not be recovered is soft deleted, so it is not shown anymore, but can be restored later + // A bundled theme whose files could not be recovered is soft deleted, so it is not shown anymore, but can be restored later. brokenTheme.IsDeleted = true; brokenTheme.IsCurrent = null; brokenTheme.UpdatedOnUtc = DateTime.UtcNow; brokenTheme.UpdatedBy = default; - Result updateResult = await unitOfWork.ThemeRepository.UpdateAsync(brokenTheme, cancellationToken); + Result updateResult = await unitOfWork.ThemeRepository.UpdateAsync(brokenTheme, cancellationToken).ConfigureAwait(false); if (updateResult.IsFailure) - _logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, updateResult.FirstError.Description); + logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, updateResult.FirstError.Description); } else { - // a user theme has no shipped archive to restore from, so damage is permanent and the theme is removed entirely - _logger.LogWarning("The stored files of user theme '{ThemeId}' are missing, so the theme is deleted.", brokenTheme.ThemeId); + // A user theme has no shipped archive to restore from, so damage is permanent and the theme is removed entirely. + logger.LogWarning("The stored files of user theme '{ThemeId}' are missing, so the theme is deleted.", brokenTheme.ThemeId); brokenTheme.IsCurrent = null; - Result deleteResult = await unitOfWork.ThemeRepository.DeleteByIdAsync(brokenTheme.Id, cancellationToken); + Result deleteResult = await unitOfWork.ThemeRepository.DeleteByIdAsync(brokenTheme.Id, cancellationToken).ConfigureAwait(false); if (deleteResult.IsFailure) - _logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, deleteResult.FirstError.Description); + logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, deleteResult.FirstError.Description); } } catch (OperationCanceledException) @@ -192,9 +173,8 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService } catch (Exception exception) { - // repairing a broken theme is best effort: an unexpected failure on one theme must not crash the host, - // so it is logged and the remaining broken themes are still processed - _logger.LogWarning(exception, "Failed to repair the broken theme '{ThemeId}'.", brokenTheme.ThemeId); + // Repairing a broken theme is best effort: an unexpected failure on one theme must not crash the host, so it is logged and the remaining broken themes are still processed. + logger.LogWarning(exception, "Failed to repair the broken theme '{ThemeId}'.", brokenTheme.ThemeId); } } } @@ -202,20 +182,21 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService /// /// Activates the configured default theme when no theme is currently active, so the application always has an active theme. /// + /// Injected service for the server-side storage and serving of theme packs. /// The unit of work for interacting with the theme repository. /// The installed themes read from the storage medium. /// Cancellation token that can be used to stop the execution. - private async Task EnsureCurrentThemeExistsAsync(IUnitOfWork unitOfWork, IReadOnlyList themes, CancellationToken cancellationToken) + private static async Task EnsureCurrentThemeExistsAsync(IThemeService themeService, IUnitOfWork unitOfWork, IReadOnlyList themes, CancellationToken cancellationToken) { if (themes.Any(theme => !theme.IsDeleted && theme.IsCurrent == true)) return; - // a theme whose files are present is preferred, so the activated theme can render immediately; a bundled theme - // whose files could not be restored is kept as the fallback, so the application always has an active theme + // A theme whose files are present is preferred, so the activated theme can render immediately; a bundled theme + // whose files could not be restored is kept as the fallback, so the application always has an active theme. ThemeEntity? defaultTheme = themes .Where(theme => !theme.IsDeleted) - .OrderBy(theme => _themeService.HasThemePack(theme.ThemeId) ? 0 : 1) - .ThenBy(theme => string.Equals(theme.ThemeId, _themeService.DefaultThemeId, StringComparison.OrdinalIgnoreCase) ? 0 : 1) + .OrderBy(theme => themeService.HasThemePack(theme.ThemeId) ? 0 : 1) + .ThenBy(theme => string.Equals(theme.ThemeId, themeService.DefaultThemeId, StringComparison.OrdinalIgnoreCase) ? 0 : 1) .ThenBy(theme => theme.ThemeId, StringComparer.OrdinalIgnoreCase) .FirstOrDefault(); if (defaultTheme is null) @@ -224,6 +205,6 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService defaultTheme.IsCurrent = true; defaultTheme.UpdatedOnUtc = DateTime.UtcNow; defaultTheme.UpdatedBy = default; - await unitOfWork.ThemeRepository.UpdateAsync(defaultTheme, cancellationToken); + await unitOfWork.ThemeRepository.UpdateAsync(defaultTheme, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs index 27275cf9..b5a4de98 100644 --- a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs +++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs @@ -20,6 +20,7 @@ using System.Linq; using System.Text; using System.Text.Json.Serialization; using System.Threading.RateLimiting; +using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.Common.DependencyInjection; @@ -128,6 +129,15 @@ public static class PresentationApiLayerServices jwtBearerOptions.Events = new JwtBearerEvents { + OnMessageReceived = jwtBearerMessageReceivedContext => // The SignalR clients send the token as a query string parameter, because the browser cannot set the Authorization header of a WebSocket connection. + { + string? accessToken = jwtBearerMessageReceivedContext.Request.Query["access_token"]; + PathString requestPath = jwtBearerMessageReceivedContext.HttpContext.Request.Path; + if (!string.IsNullOrEmpty(accessToken) && + (requestPath.StartsWithSegments("/scanProgressHub") || requestPath.StartsWithSegments("/scheduledJobsHub"))) + jwtBearerMessageReceivedContext.Token = accessToken; + return Task.CompletedTask; + }, OnChallenge = jwtBearerChallengeContext => // Event triggered when authentication is not successful for whatever reason. { jwtBearerChallengeContext.HandleResponse(); // Prevent the default 401 response. @@ -223,6 +233,10 @@ public static class PresentationApiLayerServices }); services.AddSignalR() + .AddJsonProtocol(jsonHubProtocolOptions => + // The scheduler page consumes enum values as strings (job status and task type names), so the hub must + // serialize enums the same way the REST API does, which is also configured with JsonStringEnumConverter. + jsonHubProtocolOptions.PayloadSerializerOptions.Converters.Add(new JsonStringEnumConverter())) .AddMessagePackProtocol(messagePackHubProtocolOptions => messagePackHubProtocolOptions.SerializerOptions = MessagePackSerializerOptions.Standard.WithSecurity(MessagePackSecurity.UntrustedData)); diff --git a/src/Lumina.Presentation.Api/Common/Routes/Scheduling/ApiRoutes.Scheduling.cs b/src/Lumina.Presentation.Api/Common/Routes/Scheduling/ApiRoutes.Scheduling.cs new file mode 100644 index 00000000..a57c13f9 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/Scheduling/ApiRoutes.Scheduling.cs @@ -0,0 +1,20 @@ +namespace Lumina.Presentation.Api.Common.Routes.Scheduling; + +/// +/// Class for the collection of the scheduled job routes of the API. +/// +public static partial class ApiRoutes +{ + public static class ScheduledJobs + { + public const string GET_SCHEDULED_JOBS = "/scheduled-jobs"; + public const string ADD_SCHEDULED_JOB = "/scheduled-jobs"; + public const string GET_SCHEDULED_JOB_HISTORY = "/scheduled-jobs/history"; + public const string REMOVE_SCHEDULED_JOB = "/scheduled-jobs/{scheduledJobId}"; + public const string START_SCHEDULED_JOB = "/scheduled-jobs/{scheduledJobId}/start"; + public const string STOP_SCHEDULED_JOB = "/scheduled-jobs/{scheduledJobId}/stop"; + public const string FIRE_SCHEDULED_JOB = "/scheduled-jobs/{scheduledJobId}/fire"; + public const string GET_DISPLAY_PREFERENCES = "/scheduled-jobs/display-preferences"; + public const string UPDATE_DISPLAY_PREFERENCES = "/scheduled-jobs/display-preferences"; + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/AddScheduledJob/AddScheduledJobEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/AddScheduledJob/AddScheduledJobEndpoint.cs new file mode 100644 index 00000000..226c59ba --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/AddScheduledJob/AddScheduledJobEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Application.Core.Scheduling.Commands.AddScheduledJob; +using Lumina.Contracts.Requests.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Scheduling; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Scheduling.AddScheduledJob; + +/// +/// API endpoint for the /scheduled-jobs route. +/// +public class AddScheduledJobEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _addScheduledJobCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling add scheduled job commands. + public AddScheduledJobEndpoint(ICommandHandler> addScheduledJobCommandHandler) + { + _addScheduledJobCommandHandler = addScheduledJobCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.POST); + Routes(ApiRoutes.ScheduledJobs.ADD_SCHEDULED_JOB); + Version(1); + DontCatchExceptions(); + } + + /// + /// Adds a scheduled job. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(AddScheduledJobRequest request, CancellationToken cancellationToken) + { + Result result = await _addScheduledJobCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} + + diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/AddScheduledJob/AddScheduledJobEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/AddScheduledJob/AddScheduledJobEndpointSummary.cs new file mode 100644 index 00000000..2e1c50d7 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/AddScheduledJob/AddScheduledJobEndpointSummary.cs @@ -0,0 +1,124 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Scheduling.AddScheduledJob; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class AddScheduledJobEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public AddScheduledJobEndpointSummary() + { + Summary = "Adds a scheduled job."; + Description = "Adds a scheduled job that can run its task periodically or once. Only administrators can add scheduled jobs."; + + ExampleRequest = new AddScheduledJobRequest( + Name: "Rescan media libraries", + TaskType: ScheduledTaskType.ScanMediaLibraries, + ScheduleType: ScheduleType.DailyAtHourAndMinute, + IntervalMinutes: null, + Hour: 3, + Minute: 0 + ); + + RequestParam(request => request.Name, "The name of the scheduled job. Required."); + RequestParam(request => request.TaskType, "The type of the task executed by the scheduled job. Required."); + RequestParam(request => request.ScheduleType, "The type of the schedule of the scheduled job. Required."); + RequestParam(request => request.IntervalMinutes, "The interval in minutes of the schedule, required when the schedule type is WithIntervalInMinutes."); + RequestParam(request => request.Hour, "The hour of the schedule, required when the schedule type is DailyAtHourAndMinute."); + RequestParam(request => request.Minute, "The minute of the schedule, required when the schedule type is DailyAtHourAndMinute."); + + Response(200, "The scheduled job was successfully added.", + example: new ScheduledJobResponse( + Id: Guid.NewGuid(), + Name: "Rescan media libraries", + TaskType: ScheduledTaskType.ScanMediaLibraries, + ScheduleType: ScheduleType.DailyAtHourAndMinute, + IntervalMinutes: null, + Hour: 3, + Minute: 0, + Status: ScheduledJobStatus.Added, + LastStartedOnUtc: null, + LastCompletedOnUtc: null + )); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/scheduled-jobs" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + instance = "/api/v1/scheduled-jobs" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/scheduled-jobs" + } + } + ); + + Response(403, "The request failed because the user making the request is not an administrator.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/scheduled-jobs", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/scheduled-jobs", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "ScheduledJobNameCannotBeEmpty", + "IntervalMinutesMustBePositive", + "HourMustBeBetweenZeroAndTwentyThree", + "MinuteMustBeBetweenZeroAndFiftyNine", + "InvalidScheduleType" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/FireScheduledJob/FireScheduledJobEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/FireScheduledJob/FireScheduledJobEndpoint.cs new file mode 100644 index 00000000..36ee6c7f --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/FireScheduledJob/FireScheduledJobEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Application.Core.Scheduling.Commands.FireScheduledJob; +using Lumina.Contracts.Requests.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Scheduling; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Scheduling.FireScheduledJob; + +/// +/// API endpoint for the /scheduled-jobs/{scheduledJobId}/fire route. +/// +public class FireScheduledJobEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _fireScheduledJobCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling fire scheduled job commands. + public FireScheduledJobEndpoint(ICommandHandler> fireScheduledJobCommandHandler) + { + _fireScheduledJobCommandHandler = fireScheduledJobCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.PUT); + Routes(ApiRoutes.ScheduledJobs.FIRE_SCHEDULED_JOB); + Version(1); + DontCatchExceptions(); + } + + /// + /// Fires the task of a scheduled job once, without affecting its execution cycle. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FireScheduledJobRequest request, CancellationToken cancellationToken) + { + Result result = await _fireScheduledJobCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} + + diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/FireScheduledJob/FireScheduledJobEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/FireScheduledJob/FireScheduledJobEndpointSummary.cs new file mode 100644 index 00000000..5a3d2b76 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/FireScheduledJob/FireScheduledJobEndpointSummary.cs @@ -0,0 +1,111 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Scheduling.FireScheduledJob; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class FireScheduledJobEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public FireScheduledJobEndpointSummary() + { + Summary = "Fires the task of a scheduled job once."; + Description = "Runs the task of a scheduled job once immediately, without affecting its execution cycle. Only administrators can fire scheduled jobs."; + + ExampleRequest = new FireScheduledJobRequest(ScheduledJobId: Guid.NewGuid()); + + RequestParam(request => request.ScheduledJobId, "The unique identifier of the scheduled job whose task is fired. Required."); + + Response(200, "The task of the scheduled job was successfully fired.", + example: new ScheduledJobResponse( + Id: Guid.NewGuid(), + Name: "Clean temporary files", + TaskType: ScheduledTaskType.CleanTemporaryFiles, + ScheduleType: ScheduleType.WithIntervalInMinutes, + IntervalMinutes: 1440, + Hour: null, + Minute: null, + Status: ScheduledJobStatus.Completed, + LastStartedOnUtc: DateTime.UtcNow.AddMinutes(-1), + LastCompletedOnUtc: DateTime.UtcNow + )); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/scheduled-jobs/{scheduledJobId}/fire" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + instance = "/api/v1/scheduled-jobs/{scheduledJobId}/fire" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/scheduled-jobs/{scheduledJobId}/fire" + } + } + ); + + Response(403, "The request failed because the user making the request is not an administrator, or because the task of the scheduled job is currently running.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/scheduled-jobs/{scheduledJobId}/fire", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "ScheduledJobAlreadyRunning", + instance = "/api/v1/scheduled-jobs/{scheduledJobId}/fire", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + } + ); + + Response(404, "The request failed because the provided scheduled job does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "ScheduledJobNotFound", + instance = "/api/v1/scheduled-jobs/{scheduledJobId}/fire", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/GetScheduledJobHistory/GetScheduledJobHistoryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/GetScheduledJobHistory/GetScheduledJobHistoryEndpoint.cs new file mode 100644 index 00000000..92fad950 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/GetScheduledJobHistory/GetScheduledJobHistoryEndpoint.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Application.Core.Scheduling.Queries.GetScheduledJobHistory; +using Lumina.Contracts.Requests.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Scheduling; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Scheduling.GetScheduledJobHistory; + +/// +/// API endpoint for the /scheduled-jobs/history route. +/// +public class GetScheduledJobHistoryEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getScheduledJobHistoryQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get scheduled job history queries. + public GetScheduledJobHistoryEndpoint(IQueryHandler>> getScheduledJobHistoryQueryHandler) + { + _getScheduledJobHistoryQueryHandler = getScheduledJobHistoryQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.GET); + Routes(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOB_HISTORY); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the history of the executions of the tasks of scheduled jobs. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetScheduledJobHistoryRequest request, CancellationToken cancellationToken) + { + Result> result = await _getScheduledJobHistoryQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} + + diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/GetScheduledJobHistory/GetScheduledJobHistoryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/GetScheduledJobHistory/GetScheduledJobHistoryEndpointSummary.cs new file mode 100644 index 00000000..3b26fa7f --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/GetScheduledJobHistory/GetScheduledJobHistoryEndpointSummary.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Scheduling.GetScheduledJobHistory; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetScheduledJobHistoryEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetScheduledJobHistoryEndpointSummary() + { + Summary = "Gets the history of the executions of the tasks of scheduled jobs."; + Description = "Gets the executions of the tasks of scheduled jobs that started in the requested time interval. Only administrators can get the history of scheduled jobs."; + + ExampleRequest = new GetScheduledJobHistoryRequest(From: DateTime.UtcNow.AddDays(-1), To: DateTime.UtcNow); + + RequestParam(request => request.From, "The inclusive lower bound of the interval for which the history is requested. Optional."); + RequestParam(request => request.To, "The inclusive upper bound of the interval for which the history is requested. Optional."); + + Response(200, "The execution history was successfully retrieved.", + example: new[] + { + new ScheduledJobExecutionResponse( + Id: Guid.NewGuid(), + ScheduledJobId: Guid.NewGuid(), + TaskType: ScheduledTaskType.CleanTemporaryFiles, + IsCycleRun: true, + StartedOnUtc: DateTime.UtcNow.AddMinutes(-10), + CompletedOnUtc: DateTime.UtcNow.AddMinutes(-9) + ) + }); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/scheduled-jobs/history" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + instance = "/api/v1/scheduled-jobs/history" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/scheduled-jobs/history" + } + } + ); + + Response(403, "The request failed because the user making the request is not an administrator.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/scheduled-jobs/history", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/GetScheduledJobs/GetScheduledJobsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/GetScheduledJobs/GetScheduledJobsEndpoint.cs new file mode 100644 index 00000000..23538803 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/GetScheduledJobs/GetScheduledJobsEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Scheduling.Queries.GetScheduledJobs; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Scheduling; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Scheduling.GetScheduledJobs; + +/// +/// API endpoint for the /scheduled-jobs route. +/// +public class GetScheduledJobsEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getScheduledJobsQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get scheduled jobs queries. + public GetScheduledJobsEndpoint(IQueryHandler>> getScheduledJobsQueryHandler) + { + _getScheduledJobsQueryHandler = getScheduledJobsQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.GET); + Routes(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOBS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the list of scheduled jobs. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + Result> result = await _getScheduledJobsQueryHandler.HandleAsync(new GetScheduledJobsQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} + + diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/GetScheduledJobs/GetScheduledJobsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/GetScheduledJobs/GetScheduledJobsEndpointSummary.cs new file mode 100644 index 00000000..3da4ee55 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/GetScheduledJobs/GetScheduledJobsEndpointSummary.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Scheduling.GetScheduledJobs; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetScheduledJobsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetScheduledJobsEndpointSummary() + { + Summary = "Gets the list of scheduled jobs."; + Description = "Gets the list of scheduled jobs and their status. Only administrators can get the list of scheduled jobs."; + + Response(200, "The list of scheduled jobs was successfully retrieved.", + example: new[] + { + new ScheduledJobResponse( + Id: Guid.NewGuid(), + Name: "Rescan media libraries", + TaskType: ScheduledTaskType.ScanMediaLibraries, + ScheduleType: ScheduleType.DailyAtHourAndMinute, + IntervalMinutes: null, + Hour: 3, + Minute: 0, + Status: ScheduledJobStatus.Active, + LastStartedOnUtc: DateTime.UtcNow.AddHours(-2), + LastCompletedOnUtc: DateTime.UtcNow.AddHours(-2).AddMinutes(5) + ) + }); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/scheduled-jobs" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + instance = "/api/v1/scheduled-jobs" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/scheduled-jobs" + } + } + ); + + Response(403, "The request failed because the user making the request is not an administrator.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/scheduled-jobs", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpoint.cs new file mode 100644 index 00000000..82b8cbd7 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpoint.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Scheduling.Queries.GetSchedulerDisplayPreferences; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Scheduling; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Scheduling.GetSchedulerDisplayPreferences; + +/// +/// API endpoint for the /scheduled-jobs/display-preferences route. +/// +public class GetSchedulerDisplayPreferencesEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getSchedulerDisplayPreferencesQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get scheduler display preferences queries. + public GetSchedulerDisplayPreferencesEndpoint(IQueryHandler> getSchedulerDisplayPreferencesQueryHandler) + { + _getSchedulerDisplayPreferencesQueryHandler = getSchedulerDisplayPreferencesQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.GET); + Routes(ApiRoutes.ScheduledJobs.GET_DISPLAY_PREFERENCES); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the display preferences of the scheduler page of the current user. + /// + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + Result result = await _getSchedulerDisplayPreferencesQueryHandler.HandleAsync(new GetSchedulerDisplayPreferencesQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointSummary.cs new file mode 100644 index 00000000..0bc5803c --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointSummary.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Scheduling.GetSchedulerDisplayPreferences; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetSchedulerDisplayPreferencesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetSchedulerDisplayPreferencesEndpointSummary() + { + Summary = "Gets the display preferences of the scheduler page of the current user."; + Description = "Gets the display preferences of the scheduler page of the current user. When no display preferences are stored for the user yet, the default display preferences are returned. Only administrators can use the scheduler page."; + + Response(200, "The display preferences of the scheduler page of the current user are returned.", + example: new SchedulerDisplayPreferencesResponse( + UserId: Guid.NewGuid(), + JobTypeFilter: ScheduledTaskType.ScanMediaLibraries, + DisplayTimeSpan: 10, + DisplayTimeUnit: SchedulerDisplayTimeUnit.Minutes + )); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/scheduled-jobs/display-preferences" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + instance = "/api/v1/scheduled-jobs/display-preferences" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/scheduled-jobs/display-preferences" + } + } + ); + + Response(403, "The request failed because the user making the request is not an administrator.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/scheduled-jobs/display-preferences", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/RemoveScheduledJob/RemoveScheduledJobEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/RemoveScheduledJob/RemoveScheduledJobEndpoint.cs new file mode 100644 index 00000000..e4fee510 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/RemoveScheduledJob/RemoveScheduledJobEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob; +using Lumina.Contracts.Requests.Scheduling; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Scheduling; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Scheduling.RemoveScheduledJob; + +/// +/// API endpoint for the /scheduled-jobs/{scheduledJobId} route. +/// +public class RemoveScheduledJobEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _removeScheduledJobCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling remove scheduled job commands. + public RemoveScheduledJobEndpoint(ICommandHandler> removeScheduledJobCommandHandler) + { + _removeScheduledJobCommandHandler = removeScheduledJobCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.DELETE); + Routes(ApiRoutes.ScheduledJobs.REMOVE_SCHEDULED_JOB); + Version(1); + DontCatchExceptions(); + } + + /// + /// Removes a scheduled job. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(RemoveScheduledJobRequest request, CancellationToken cancellationToken) + { + Result result = await _removeScheduledJobCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(_ => TypedResults.Ok(new { }), Problem); + } +} + + diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/RemoveScheduledJob/RemoveScheduledJobEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/RemoveScheduledJob/RemoveScheduledJobEndpointSummary.cs new file mode 100644 index 00000000..840c9b3a --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/RemoveScheduledJob/RemoveScheduledJobEndpointSummary.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Scheduling; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Scheduling.RemoveScheduledJob; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class RemoveScheduledJobEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public RemoveScheduledJobEndpointSummary() + { + Summary = "Removes a scheduled job."; + Description = "Removes a scheduled job, after stopping its execution cycle, if it has one. Only administrators can remove scheduled jobs."; + + ExampleRequest = new RemoveScheduledJobRequest(ScheduledJobId: Guid.NewGuid()); + + RequestParam(request => request.ScheduledJobId, "The unique identifier of the scheduled job to remove. Required."); + + Response(200, "The scheduled job was successfully removed."); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/scheduled-jobs/{scheduledJobId}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + instance = "/api/v1/scheduled-jobs/{scheduledJobId}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/scheduled-jobs/{scheduledJobId}" + } + } + ); + + Response(403, "The request failed because the user making the request is not an administrator.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/scheduled-jobs/{scheduledJobId}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the provided scheduled job does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "ScheduledJobNotFound", + instance = "/api/v1/scheduled-jobs/{scheduledJobId}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/StartScheduledJob/StartScheduledJobEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/StartScheduledJob/StartScheduledJobEndpoint.cs new file mode 100644 index 00000000..7c89ed36 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/StartScheduledJob/StartScheduledJobEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Application.Core.Scheduling.Commands.StartScheduledJob; +using Lumina.Contracts.Requests.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Scheduling; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Scheduling.StartScheduledJob; + +/// +/// API endpoint for the /scheduled-jobs/{scheduledJobId}/start route. +/// +public class StartScheduledJobEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _startScheduledJobCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling start scheduled job commands. + public StartScheduledJobEndpoint(ICommandHandler> startScheduledJobCommandHandler) + { + _startScheduledJobCommandHandler = startScheduledJobCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.PUT); + Routes(ApiRoutes.ScheduledJobs.START_SCHEDULED_JOB); + Version(1); + DontCatchExceptions(); + } + + /// + /// Starts the execution cycle of a scheduled job. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(StartScheduledJobRequest request, CancellationToken cancellationToken) + { + Result result = await _startScheduledJobCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} + + diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/StartScheduledJob/StartScheduledJobEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/StartScheduledJob/StartScheduledJobEndpointSummary.cs new file mode 100644 index 00000000..d8f6e779 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/StartScheduledJob/StartScheduledJobEndpointSummary.cs @@ -0,0 +1,111 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Scheduling.StartScheduledJob; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class StartScheduledJobEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public StartScheduledJobEndpointSummary() + { + Summary = "Starts the execution cycle of a scheduled job."; + Description = "Starts the execution cycle of a scheduled job, which runs its task once immediately and then on its schedule. Only administrators can start scheduled jobs."; + + ExampleRequest = new StartScheduledJobRequest(ScheduledJobId: Guid.NewGuid()); + + RequestParam(request => request.ScheduledJobId, "The unique identifier of the scheduled job whose execution cycle is started. Required."); + + Response(200, "The execution cycle of the scheduled job was successfully started.", + example: new ScheduledJobResponse( + Id: Guid.NewGuid(), + Name: "Rescan media libraries", + TaskType: ScheduledTaskType.ScanMediaLibraries, + ScheduleType: ScheduleType.DailyAtHourAndMinute, + IntervalMinutes: null, + Hour: 3, + Minute: 0, + Status: ScheduledJobStatus.Active, + LastStartedOnUtc: DateTime.UtcNow.AddMinutes(-1), + LastCompletedOnUtc: null + )); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/scheduled-jobs/{scheduledJobId}/start" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + instance = "/api/v1/scheduled-jobs/{scheduledJobId}/start" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/scheduled-jobs/{scheduledJobId}/start" + } + } + ); + + Response(403, "The request failed because the user making the request is not an administrator, or because the execution cycle of the scheduled job is already started.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/scheduled-jobs/{scheduledJobId}/start", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "ScheduledJobCycleAlreadyStarted", + instance = "/api/v1/scheduled-jobs/{scheduledJobId}/start", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + } + ); + + Response(404, "The request failed because the provided scheduled job does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "ScheduledJobNotFound", + instance = "/api/v1/scheduled-jobs/{scheduledJobId}/start", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/StopScheduledJob/StopScheduledJobEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/StopScheduledJob/StopScheduledJobEndpoint.cs new file mode 100644 index 00000000..4b409034 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/StopScheduledJob/StopScheduledJobEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Application.Core.Scheduling.Commands.StopScheduledJob; +using Lumina.Contracts.Requests.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Scheduling; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Scheduling.StopScheduledJob; + +/// +/// API endpoint for the /scheduled-jobs/{scheduledJobId}/stop route. +/// +public class StopScheduledJobEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _stopScheduledJobCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling stop scheduled job commands. + public StopScheduledJobEndpoint(ICommandHandler> stopScheduledJobCommandHandler) + { + _stopScheduledJobCommandHandler = stopScheduledJobCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.PUT); + Routes(ApiRoutes.ScheduledJobs.STOP_SCHEDULED_JOB); + Version(1); + DontCatchExceptions(); + } + + /// + /// Stops the execution cycle of a scheduled job. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(StopScheduledJobRequest request, CancellationToken cancellationToken) + { + Result result = await _stopScheduledJobCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} + + diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/StopScheduledJob/StopScheduledJobEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/StopScheduledJob/StopScheduledJobEndpointSummary.cs new file mode 100644 index 00000000..bd372604 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/StopScheduledJob/StopScheduledJobEndpointSummary.cs @@ -0,0 +1,120 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Scheduling.StopScheduledJob; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class StopScheduledJobEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public StopScheduledJobEndpointSummary() + { + Summary = "Stops the execution cycle of a scheduled job."; + Description = "Stops the execution cycle of a scheduled job, without removing it. Only administrators can stop scheduled jobs."; + + ExampleRequest = new StopScheduledJobRequest(ScheduledJobId: Guid.NewGuid()); + + RequestParam(request => request.ScheduledJobId, "The unique identifier of the scheduled job whose execution cycle is stopped. Required."); + + Response(200, "The execution cycle of the scheduled job was successfully stopped.", + example: new ScheduledJobResponse( + Id: Guid.NewGuid(), + Name: "Rescan media libraries", + TaskType: ScheduledTaskType.ScanMediaLibraries, + ScheduleType: ScheduleType.DailyAtHourAndMinute, + IntervalMinutes: null, + Hour: 3, + Minute: 0, + Status: ScheduledJobStatus.Added, + LastStartedOnUtc: DateTime.UtcNow.AddMinutes(-1), + LastCompletedOnUtc: DateTime.UtcNow + )); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/scheduled-jobs/{scheduledJobId}/stop" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + instance = "/api/v1/scheduled-jobs/{scheduledJobId}/stop" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/scheduled-jobs/{scheduledJobId}/stop" + } + } + ); + + Response(403, "The request failed because the user making the request is not an administrator, or because the execution cycle of the scheduled job was not started, or its task is currently running.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/scheduled-jobs/{scheduledJobId}/stop", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "ScheduledJobNotStarted", + instance = "/api/v1/scheduled-jobs/{scheduledJobId}/stop", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "ScheduledJobAlreadyRunning", + instance = "/api/v1/scheduled-jobs/{scheduledJobId}/stop", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + } + ); + + Response(404, "The request failed because the provided scheduled job does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "ScheduledJobNotFound", + instance = "/api/v1/scheduled-jobs/{scheduledJobId}/stop", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpoint.cs new file mode 100644 index 00000000..05b7323c --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpoint.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Application.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences; +using Lumina.Contracts.Requests.Scheduling; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Scheduling; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Scheduling.UpdateSchedulerDisplayPreferences; + +/// +/// API endpoint for the /scheduled-jobs/display-preferences route. +/// +public class UpdateSchedulerDisplayPreferencesEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _updateSchedulerDisplayPreferencesCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling update scheduler display preferences commands. + public UpdateSchedulerDisplayPreferencesEndpoint(ICommandHandler> updateSchedulerDisplayPreferencesCommandHandler) + { + _updateSchedulerDisplayPreferencesCommandHandler = updateSchedulerDisplayPreferencesCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.PUT); + Routes(ApiRoutes.ScheduledJobs.UPDATE_DISPLAY_PREFERENCES); + Version(1); + DontCatchExceptions(); + } + + /// + /// Updates the display preferences of the scheduler page of the current user. + /// + /// The request containing the display preferences of the scheduler page of the current user. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(UpdateSchedulerDisplayPreferencesRequest request, CancellationToken cancellationToken) + { + Result result = await _updateSchedulerDisplayPreferencesCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointSummary.cs new file mode 100644 index 00000000..b3fdf077 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Scheduling/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointSummary.cs @@ -0,0 +1,100 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Scheduling; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Scheduling.UpdateSchedulerDisplayPreferences; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdateSchedulerDisplayPreferencesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateSchedulerDisplayPreferencesEndpointSummary() + { + Summary = "Updates the display preferences of the scheduler page of the current user."; + Description = "Updates the display preferences of the scheduler page of the current user. Only administrators can use the scheduler page."; + + ExampleRequest = new UpdateSchedulerDisplayPreferencesRequest( + JobTypeFilter: ScheduledTaskType.ScanMediaLibraries, + DisplayTimeSpan: 10, + DisplayTimeUnit: SchedulerDisplayTimeUnit.Minutes + ); + + RequestParam(request => request.JobTypeFilter, "The type of the scheduled job tasks whose executions are shown on the scheduler page, or null when all of them are shown."); + RequestParam(request => request.DisplayTimeSpan, "The time span, expressed in the display time unit, that the scheduler page shows. Required."); + RequestParam(request => request.DisplayTimeUnit, "The unit in which the displayed time span of the scheduler page is expressed. Required."); + + Response(200, "The display preferences of the scheduler page of the current user were successfully updated."); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/scheduled-jobs/display-preferences" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + instance = "/api/v1/scheduled-jobs/display-preferences" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/scheduled-jobs/display-preferences" + } + } + ); + + Response(403, "The request failed because the user making the request is not an administrator.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/scheduled-jobs/display-preferences", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/scheduled-jobs/display-preferences", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "SchedulerDisplayTimeSpanMustBePositive" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip b/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip index 10e5b73d..692ed829 100644 Binary files a/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip and b/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip differ diff --git a/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip b/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip index 23530892..fa23d569 100644 Binary files a/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip and b/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip differ diff --git a/src/Lumina.Presentation.Api/Program.cs b/src/Lumina.Presentation.Api/Program.cs index 00422fe1..811b1de9 100644 --- a/src/Lumina.Presentation.Api/Program.cs +++ b/src/Lumina.Presentation.Api/Program.cs @@ -8,6 +8,7 @@ using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Infrastructure.Common.DependencyInjection; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress; +using Lumina.Infrastructure.Core.Scheduling.Notifications; using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; using Lumina.Presentation.Api.Common.DependencyInjection; using Lumina.Presentation.Api.Common.Middlewares; @@ -133,7 +134,7 @@ public class Program // Add API documentation (OpenApi/Scalar). app.MapOpenApi(); - app.UseOpenApi(openApiDocumentMiddlewareSettings => openApiDocumentMiddlewareSettings.Path = "/openapi/{documentName}.json"); // this is needed for API versioning to work correctly with Scalar + app.UseOpenApi(openApiDocumentMiddlewareSettings => openApiDocumentMiddlewareSettings.Path = "/openapi/{documentName}.json"); // This is needed for API versioning to work correctly with Scalar. app.MapScalarApiReference(scalarOptions => { scalarOptions.WithTitle("Lumina API") @@ -145,7 +146,9 @@ public class Program // Add the middleware that fires domain events and ensures eventual transactional consistency, but NOT for long-polling/WebSockets stuff like SignalR, which would keep the db locked, // and NOT for the health probes, which would otherwise begin a database transaction on every probe. - app.UseWhen(ctx => !ctx.Request.Path.StartsWithSegments("/scanProgressHub") && !ctx.Request.Path.StartsWithSegments("/health"), app => app.UseMiddleware()); + app.UseWhen(ctx => !ctx.Request.Path.StartsWithSegments("/scanProgressHub") && + !ctx.Request.Path.StartsWithSegments("/scheduledJobsHub") && + !ctx.Request.Path.StartsWithSegments("/health"), app => app.UseMiddleware()); // Create a directory relative to the application's startup directory, and use it to store static files that are served at the /media route on the API. string mediaRootDirectoryPathSetting = app.Configuration.GetValue("MediaSettings:RootDirectory") ?? string.Empty; @@ -176,13 +179,14 @@ public class Program RequestPath = "/media", OnPrepareResponse = staticFileContext => { - // the served media must not run as active content, so that attacker-influenced files (e.g. SVG covers) cannot execute scripts on the API origin + // The served media must not run as active content, so that attacker-influenced files (e.g. SVG covers) cannot execute scripts on the API origin. staticFileContext.Context.Response.Headers["X-Content-Type-Options"] = "nosniff"; staticFileContext.Context.Response.Headers["Content-Security-Policy"] = "default-src 'none'; script-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:"; } }); app.MapHub("/scanProgressHub"); + app.MapHub("/scheduledJobsHub"); // The liveness probe reports whether the process is running, while the readiness probe also verifies that the database is reachable. app.MapHealthChecks("/health/live", new HealthCheckOptions diff --git a/src/Lumina.Presentation.Web/Common/DTO/Scheduling/ScheduledJobDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Scheduling/ScheduledJobDto.cs new file mode 100644 index 00000000..137e8445 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Scheduling/ScheduledJobDto.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.Scheduling; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Scheduling; + +/// +/// Data transfer object for a scheduled job. +/// +/// The unique identifier of the scheduled job. +/// The name of the scheduled job. +/// The type of the task executed by the scheduled job. +/// The type of the schedule of the scheduled job. +/// The interval in minutes of the schedule of the scheduled job. +/// The hour of the schedule of the scheduled job. +/// The minute of the schedule of the scheduled job. +/// The status of the scheduled job. +/// The optional date and time when the task of the scheduled job last started its execution. +/// The optional date and time when the task of the scheduled job last completed its execution. +[DebuggerDisplay("Id: {Id}, Name: {Name}, Status: {Status}")] +public record ScheduledJobDto( + Guid Id, + string Name, + ScheduledTaskType TaskType, + ScheduleType ScheduleType, + int? IntervalMinutes, + int? Hour, + int? Minute, + ScheduledJobStatus Status, + DateTime? LastStartedOnUtc, + DateTime? LastCompletedOnUtc +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Scheduling/ScheduledJobExecutionDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Scheduling/ScheduledJobExecutionDto.cs new file mode 100644 index 00000000..c3d68e9f --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Scheduling/ScheduledJobExecutionDto.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.Scheduling; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Scheduling; + +/// +/// Data transfer object for an execution of the task of a scheduled job. +/// +/// The unique identifier of the execution. +/// The unique identifier of the scheduled job whose task was executed. +/// The type of the task that was executed. +/// when the execution was triggered by the execution cycle of the scheduled job. +/// The date and time when the execution started. +/// The optional date and time when the execution completed. +[DebuggerDisplay("Id: {Id}, ScheduledJobId: {ScheduledJobId}")] +public record ScheduledJobExecutionDto( + Guid Id, + Guid ScheduledJobId, + ScheduledTaskType TaskType, + bool IsCycleRun, + DateTime StartedOnUtc, + DateTime? CompletedOnUtc +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Scheduling/SchedulerDisplayPreferencesDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Scheduling/SchedulerDisplayPreferencesDto.cs new file mode 100644 index 00000000..cfc7e759 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Scheduling/SchedulerDisplayPreferencesDto.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.Scheduling; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Scheduling; + +/// +/// Data transfer object for the display preferences of the scheduler page. +/// +/// The unique identifier of the user that owns the display preferences. +/// The type of the scheduled job tasks whose executions are shown on the scheduler page, or when all of them are shown. +/// The time span, expressed in , that the scheduler page shows. +/// The unit in which the displayed time span of the scheduler page is expressed. +[DebuggerDisplay("UserId: {UserId}, DisplayTimeSpan: {DisplayTimeSpan} {DisplayTimeUnit}")] +public record SchedulerDisplayPreferencesDto( + Guid UserId, + ScheduledTaskType? JobTypeFilter, + int DisplayTimeSpan, + SchedulerDisplayTimeUnit DisplayTimeUnit +); diff --git a/src/Lumina.Presentation.Web/Common/Enums/Scheduling/ScheduleType.cs b/src/Lumina.Presentation.Web/Common/Enums/Scheduling/ScheduleType.cs new file mode 100644 index 00000000..409eff26 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Enums/Scheduling/ScheduleType.cs @@ -0,0 +1,22 @@ +namespace Lumina.Presentation.Web.Common.Enums.Scheduling; + +/// +/// Enumeration for the types of schedules of scheduled jobs. +/// +public enum ScheduleType +{ + /// + /// The scheduled job repeats with an interval measured in minutes. + /// + WithIntervalInMinutes, + + /// + /// The scheduled job repeats daily at a fixed hour and minute. + /// + DailyAtHourAndMinute, + + /// + /// The scheduled job fires its task once, every time the application starts. + /// + OnceAtStartup +} diff --git a/src/Lumina.Presentation.Web/Common/Enums/Scheduling/ScheduledJobStatus.cs b/src/Lumina.Presentation.Web/Common/Enums/Scheduling/ScheduledJobStatus.cs new file mode 100644 index 00000000..0f1eb0fd --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Enums/Scheduling/ScheduledJobStatus.cs @@ -0,0 +1,27 @@ +namespace Lumina.Presentation.Web.Common.Enums.Scheduling; + +/// +/// Enumeration for the statuses of scheduled jobs. +/// +public enum ScheduledJobStatus +{ + /// + /// The scheduled job was added, but its execution cycle was not started. + /// + Added, + + /// + /// The execution cycle of the scheduled job is active, and the job is waiting for its next scheduled execution. + /// + Active, + + /// + /// The task of the scheduled job is currently being executed. + /// + Running, + + /// + /// The scheduled job finished its latest one time execution. + /// + Completed +} diff --git a/src/Lumina.Presentation.Web/Common/Enums/Scheduling/ScheduledTaskType.cs b/src/Lumina.Presentation.Web/Common/Enums/Scheduling/ScheduledTaskType.cs new file mode 100644 index 00000000..5f033276 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Enums/Scheduling/ScheduledTaskType.cs @@ -0,0 +1,27 @@ +namespace Lumina.Presentation.Web.Common.Enums.Scheduling; + +/// +/// Enumeration for the types of tasks a scheduled job can execute. +/// +public enum ScheduledTaskType +{ + /// + /// The scheduled job scans all enabled media libraries. + /// + ScanMediaLibraries, + + /// + /// The scheduled job cleans the temporary directory of the application. + /// + CleanTemporaryFiles, + + /// + /// The scheduled job repairs the installed themes whose files are missing. + /// + RepairThemes, + + /// + /// The scheduled job cleans the execution history of the scheduled jobs, keeping only the recent executions. + /// + CleanScheduledJobExecutionHistory +} diff --git a/src/Lumina.Presentation.Web/Common/Enums/Scheduling/SchedulerDisplayTimeUnit.cs b/src/Lumina.Presentation.Web/Common/Enums/Scheduling/SchedulerDisplayTimeUnit.cs new file mode 100644 index 00000000..1c545952 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Enums/Scheduling/SchedulerDisplayTimeUnit.cs @@ -0,0 +1,22 @@ +namespace Lumina.Presentation.Web.Common.Enums.Scheduling; + +/// +/// Enumeration for the units in which the display time span of the scheduler page is expressed. +/// +public enum SchedulerDisplayTimeUnit +{ + /// + /// The display time span is expressed in minutes. + /// + Minutes, + + /// + /// The display time span is expressed in hours. + /// + Hours, + + /// + /// The display time span is expressed in days. + /// + Days +} diff --git a/src/Lumina.Presentation.Web/Common/Requests/Scheduling/AddScheduledJobRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Scheduling/AddScheduledJobRequest.cs new file mode 100644 index 00000000..e1c2b735 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Scheduling/AddScheduledJobRequest.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.Scheduling; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Scheduling; + +/// +/// Request for adding a scheduled job. +/// +/// The name of the scheduled job. Required. +/// The type of the task executed by the scheduled job. Required. +/// The type of the schedule of the scheduled job. Required. +/// The interval in minutes of the schedule, when the schedule type is . +/// The hour of the schedule, when the schedule type is . +/// The minute of the schedule, when the schedule type is . +[DebuggerDisplay("Name: {Name}")] +public record AddScheduledJobRequest( + string Name, + ScheduledTaskType TaskType, + ScheduleType ScheduleType, + int? IntervalMinutes, + int? Hour, + int? Minute +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Scheduling/FireScheduledJobRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Scheduling/FireScheduledJobRequest.cs new file mode 100644 index 00000000..188458f1 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Scheduling/FireScheduledJobRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Scheduling; + +/// +/// Request for firing the task of a scheduled job once. +/// +/// The unique identifier of the scheduled job whose task is fired. Required. +[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")] +public record FireScheduledJobRequest( + Guid ScheduledJobId +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Scheduling/GetScheduledJobHistoryRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Scheduling/GetScheduledJobHistoryRequest.cs new file mode 100644 index 00000000..6d3082b9 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Scheduling/GetScheduledJobHistoryRequest.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Scheduling; + +/// +/// Request for getting the history of the executions of the tasks of scheduled jobs. +/// +/// The inclusive lower bound of the interval for which the history is requested. Optional. +/// The inclusive upper bound of the interval for which the history is requested. Optional. +[DebuggerDisplay("From: {From}, To: {To}")] +public record GetScheduledJobHistoryRequest( + DateTime? From, + DateTime? To +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Scheduling/RemoveScheduledJobRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Scheduling/RemoveScheduledJobRequest.cs new file mode 100644 index 00000000..d55cf0c5 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Scheduling/RemoveScheduledJobRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Scheduling; + +/// +/// Request for removing a scheduled job. +/// +/// The unique identifier of the scheduled job to remove. Required. +[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")] +public record RemoveScheduledJobRequest( + Guid ScheduledJobId +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Scheduling/StartScheduledJobRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Scheduling/StartScheduledJobRequest.cs new file mode 100644 index 00000000..735213e6 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Scheduling/StartScheduledJobRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Scheduling; + +/// +/// Request for starting the execution cycle of a scheduled job. +/// +/// The unique identifier of the scheduled job whose execution cycle is started. Required. +[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")] +public record StartScheduledJobRequest( + Guid ScheduledJobId +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Scheduling/StopScheduledJobRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Scheduling/StopScheduledJobRequest.cs new file mode 100644 index 00000000..a081384a --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Scheduling/StopScheduledJobRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Scheduling; + +/// +/// Request for stopping the execution cycle of a scheduled job. +/// +/// The unique identifier of the scheduled job whose execution cycle is stopped. Required. +[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")] +public record StopScheduledJobRequest( + Guid ScheduledJobId +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Scheduling/UpdateSchedulerDisplayPreferencesRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Scheduling/UpdateSchedulerDisplayPreferencesRequest.cs new file mode 100644 index 00000000..bfae4a55 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Scheduling/UpdateSchedulerDisplayPreferencesRequest.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.Scheduling; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Scheduling; + +/// +/// Request for updating the display preferences of the scheduler page of the current user. +/// +/// The type of the scheduled job tasks whose executions are shown on the scheduler page, or when all of them are shown. +/// The time span, expressed in , that the scheduler page shows. Required. +/// The unit in which the displayed time span of the scheduler page is expressed. Required. +[DebuggerDisplay("DisplayTimeSpan: {DisplayTimeSpan} {DisplayTimeUnit}")] +public record UpdateSchedulerDisplayPreferencesRequest( + ScheduledTaskType? JobTypeFilter, + int DisplayTimeSpan, + SchedulerDisplayTimeUnit DisplayTimeUnit +); diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Scheduling.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Scheduling.cs new file mode 100644 index 00000000..27b85cac --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Scheduling.cs @@ -0,0 +1,23 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of remote API routes called by this Web application. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the scheduled job endpoints of the remote API. + /// + public static class ScheduledJobs + { + public const string GET_SCHEDULED_JOBS = "scheduled-jobs"; + public const string ADD_SCHEDULED_JOB = "scheduled-jobs"; + public const string GET_SCHEDULED_JOB_HISTORY = "scheduled-jobs/history"; + public const string REMOVE_SCHEDULED_JOB = "scheduled-jobs/{scheduledJobId}"; + public const string START_SCHEDULED_JOB = "scheduled-jobs/{scheduledJobId}/start"; + public const string STOP_SCHEDULED_JOB = "scheduled-jobs/{scheduledJobId}/stop"; + public const string FIRE_SCHEDULED_JOB = "scheduled-jobs/{scheduledJobId}/fire"; + public const string GET_DISPLAY_PREFERENCES = "scheduled-jobs/display-preferences"; + public const string UPDATE_DISPLAY_PREFERENCES = "scheduled-jobs/display-preferences"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Authentication.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Authentication.cs index 60cb1ced..a545d7ba 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Authentication.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Authentication.cs @@ -17,6 +17,7 @@ public static partial class WebRoutes public const string PROFILE_VIEW = "{culture}/auth/profile"; public const string ACCESS_DENIED_VIEW = "{culture}/auth/access-denied"; public const string LOGOUT = "{culture}/auth/logout"; + public const string GET_API_ACCESS_TOKEN = "{culture}/auth/api-access-token"; public const string REGISTER = "{culture}/auth/api-register"; public const string LOGIN = "{culture}/auth/api-login"; public const string RECOVER_PASSWORD = "{culture}/auth/api-recover-password"; diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Scheduler.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Scheduler.cs new file mode 100644 index 00000000..c8694626 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Scheduler.cs @@ -0,0 +1,24 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of routes defined in the Web application. +/// +public static partial class WebRoutes +{ + /// + /// Routes for the scheduled jobs pages. + /// + public static class Scheduler + { + public const string INDEX = "{culture}/admin/scheduled-jobs"; + public const string GET_SCHEDULED_JOBS = "{culture}/admin/api-scheduled-jobs"; + public const string ADD_SCHEDULED_JOB = "{culture}/admin/api-scheduled-jobs/add"; + public const string GET_SCHEDULED_JOB_HISTORY = "{culture}/admin/api-scheduled-jobs/history"; + public const string REMOVE_SCHEDULED_JOB = "{culture}/admin/api-scheduled-jobs/{scheduledJobId}"; + public const string START_SCHEDULED_JOB = "{culture}/admin/api-scheduled-jobs/{scheduledJobId}/start"; + public const string STOP_SCHEDULED_JOB = "{culture}/admin/api-scheduled-jobs/{scheduledJobId}/stop"; + public const string FIRE_SCHEDULED_JOB = "{culture}/admin/api-scheduled-jobs/{scheduledJobId}/fire"; + public const string GET_DISPLAY_PREFERENCES = "{culture}/admin/api-scheduled-jobs/display-preferences"; + public const string UPDATE_DISPLAY_PREFERENCES = "{culture}/admin/api-scheduled-jobs/display-preferences"; + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpoint.cs new file mode 100644 index 00000000..628f529d --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.AddScheduledJob; + +/// +/// API endpoint for the /{culture}/admin/api-scheduled-jobs/add route. +/// +public class AddScheduledJobEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public AddScheduledJobEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.Scheduler.ADD_SCHEDULED_JOB); + DontAutoTag(); + Options(options => options.WithTags("Admin")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + EnableAntiforgery(); + } + + /// + /// Adds a scheduled job. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(AddScheduledJobRequest request, CancellationToken cancellationToken) + { + ScheduledJobDto scheduledJob = await _apiHttpClient.PostAsync(ApiRoutes.ScheduledJobs.ADD_SCHEDULED_JOB, request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(scheduledJob); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointSummary.cs new file mode 100644 index 00000000..c3e60663 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointSummary.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Common.Enums.Scheduling; +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.AddScheduledJob; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class AddScheduledJobEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public AddScheduledJobEndpointSummary() + { + Summary = "Adds a scheduled job."; + Description = "Adds a scheduled job that can run its task periodically or once."; + + RequestParam(r => r.Name, "The name of the scheduled job. Required."); + RequestParam(r => r.TaskType, "The type of the task executed by the scheduled job. Required."); + RequestParam(r => r.ScheduleType, "The type of the schedule of the scheduled job. Required."); + RequestParam(r => r.IntervalMinutes, "The interval in minutes of the schedule, when the schedule type is WithIntervalInMinutes."); + RequestParam(r => r.Hour, "The hour of the schedule, when the schedule type is DailyAtHourAndMinute."); + RequestParam(r => r.Minute, "The minute of the schedule, when the schedule type is DailyAtHourAndMinute."); + + ExampleRequest = new AddScheduledJobRequest( + Name: "Rescan media libraries", + TaskType: ScheduledTaskType.ScanMediaLibraries, + ScheduleType: ScheduleType.DailyAtHourAndMinute, + IntervalMinutes: null, + Hour: 3, + Minute: 0 + ); + + Response(200, "The scheduled job was successfully added.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpoint.cs new file mode 100644 index 00000000..0688c4c9 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.FireScheduledJob; + +/// +/// API endpoint for the /{culture}/admin/api-scheduled-jobs/{scheduledJobId}/fire route. +/// +public class FireScheduledJobEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public FireScheduledJobEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.PUT); + Routes(WebRoutes.Scheduler.FIRE_SCHEDULED_JOB); + DontAutoTag(); + Options(options => options.WithTags("Admin")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + EnableAntiforgery(); + } + + /// + /// Fires the task of a scheduled job once, without affecting its execution cycle. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FireScheduledJobRequest request, CancellationToken cancellationToken) + { + await _apiHttpClient.PutAsync(ApiRoutes.ScheduledJobs.FIRE_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false); + return JsonSuccess(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointSummary.cs new file mode 100644 index 00000000..0b1e792a --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointSummary.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.FireScheduledJob; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class FireScheduledJobEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public FireScheduledJobEndpointSummary() + { + Summary = "Fires the task of a scheduled job."; + Description = "Runs the task of the scheduled job identified by the request once immediately, without affecting its execution cycle."; + + RequestParam(r => r.ScheduledJobId, "The unique identifier of the scheduled job whose task is fired. Required."); + + ExampleRequest = new FireScheduledJobRequest(ScheduledJobId: Guid.NewGuid()); + + Response(200, "The task of the scheduled job was successfully fired.", example: new SuccessResponse(true)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpoint.cs new file mode 100644 index 00000000..b554dd25 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpoint.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.GetScheduledJobHistory; + +/// +/// API endpoint for the /{culture}/admin/api-scheduled-jobs/history route. +/// +public class GetScheduledJobHistoryEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetScheduledJobHistoryEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Scheduler.GET_SCHEDULED_JOB_HISTORY); + DontAutoTag(); + Options(options => options.WithTags("Admin")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + } + + /// + /// Gets the history of the executions of the tasks of scheduled jobs. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetScheduledJobHistoryRequest request, CancellationToken cancellationToken) + { + ScheduledJobExecutionDto[] executions = await _apiHttpClient.GetAsync(BuildHistoryEndpoint(request), cancellationToken).ConfigureAwait(false); + return JsonSuccess(executions); + } + + /// + /// Builds the API endpoint used to get the history of the executions of the tasks of scheduled jobs, from the provided . + /// + /// The request object. + /// The API endpoint to which the history request is sent. + private static string BuildHistoryEndpoint(GetScheduledJobHistoryRequest request) + { + StringBuilder endpoint = new(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOB_HISTORY); + if (request.From is not null || request.To is not null) + { + endpoint.Append('?'); + if (request.From is not null) + endpoint.Append($"from={Uri.EscapeDataString(request.From.Value.ToString("o"))}"); + if (request.To is not null) + { + if (request.From is not null) + endpoint.Append('&'); + endpoint.Append($"to={Uri.EscapeDataString(request.To.Value.ToString("o"))}"); + } + } + return endpoint.ToString(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointSummary.cs new file mode 100644 index 00000000..49182352 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointSummary.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.GetScheduledJobHistory; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetScheduledJobHistoryEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetScheduledJobHistoryEndpointSummary() + { + Summary = "Gets the history of the executions of the tasks of scheduled jobs."; + Description = "Retrieves the executions of the tasks of scheduled jobs that started in the requested time interval."; + + RequestParam(r => r.From, "The inclusive lower bound of the interval for which the history is requested. Optional."); + RequestParam(r => r.To, "The inclusive upper bound of the interval for which the history is requested. Optional."); + + ExampleRequest = new GetScheduledJobHistoryRequest(From: DateTime.UtcNow.AddDays(-1), To: DateTime.UtcNow); + + Response(200, "The execution history of the tasks of the scheduled jobs is returned.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpoint.cs new file mode 100644 index 00000000..d227e45a --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.GetScheduledJobs; + +/// +/// API endpoint for the /{culture}/admin/api-scheduled-jobs route. +/// +public class GetScheduledJobsEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetScheduledJobsEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Scheduler.GET_SCHEDULED_JOBS); + DontAutoTag(); + Options(options => options.WithTags("Admin")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + } + + /// + /// Gets the list of scheduled jobs. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + ScheduledJobDto[] scheduledJobs = await _apiHttpClient.GetAsync(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOBS, cancellationToken).ConfigureAwait(false); + return JsonSuccess(scheduledJobs); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointSummary.cs new file mode 100644 index 00000000..c4f3ffaa --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointSummary.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Scheduling; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.GetScheduledJobs; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetScheduledJobsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetScheduledJobsEndpointSummary() + { + Summary = "Gets the list of scheduled jobs."; + Description = "Retrieves the list of scheduled jobs and their status."; + + Response(200, "The list of scheduled jobs is returned.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpoint.cs new file mode 100644 index 00000000..2f8684fd --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.GetSchedulerDisplayPreferences; + +/// +/// API endpoint for the /{culture}/admin/api-scheduled-jobs/display-preferences route. +/// +public class GetSchedulerDisplayPreferencesEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetSchedulerDisplayPreferencesEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Scheduler.GET_DISPLAY_PREFERENCES); + DontAutoTag(); + Options(options => options.WithTags("Admin")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + } + + /// + /// Gets the display preferences of the scheduler page of the current user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + SchedulerDisplayPreferencesDto displayPreferences = await _apiHttpClient.GetAsync(ApiRoutes.ScheduledJobs.GET_DISPLAY_PREFERENCES, cancellationToken).ConfigureAwait(false); + return JsonSuccess(displayPreferences); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointSummary.cs new file mode 100644 index 00000000..5a4c38e9 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointSummary.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Common.Enums.Scheduling; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.GetSchedulerDisplayPreferences; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetSchedulerDisplayPreferencesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetSchedulerDisplayPreferencesEndpointSummary() + { + Summary = "Gets the display preferences of the scheduler page."; + Description = "Retrieves the display preferences of the scheduler page of the current user, or the default display preferences when none are stored yet."; + + Response(200, "The display preferences of the scheduler page are returned.", example: new SuccessResponse(true, new SchedulerDisplayPreferencesDto( + UserId: Guid.NewGuid(), + JobTypeFilter: ScheduledTaskType.ScanMediaLibraries, + DisplayTimeSpan: 10, + DisplayTimeUnit: SchedulerDisplayTimeUnit.Minutes + ))); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpoint.cs new file mode 100644 index 00000000..7ad9a8b1 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.RemoveScheduledJob; + +/// +/// API endpoint for the /{culture}/admin/api-scheduled-jobs/{scheduledJobId} route. +/// +public class RemoveScheduledJobEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public RemoveScheduledJobEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.DELETE); + Routes(WebRoutes.Scheduler.REMOVE_SCHEDULED_JOB); + DontAutoTag(); + Options(options => options.WithTags("Admin")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + EnableAntiforgery(); + } + + /// + /// Removes a scheduled job. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(RemoveScheduledJobRequest request, CancellationToken cancellationToken) + { + await _apiHttpClient.DeleteAsync(ApiRoutes.ScheduledJobs.REMOVE_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), cancellationToken).ConfigureAwait(false); + return JsonSuccess(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointSummary.cs new file mode 100644 index 00000000..3e18499e --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointSummary.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.RemoveScheduledJob; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class RemoveScheduledJobEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public RemoveScheduledJobEndpointSummary() + { + Summary = "Removes a scheduled job."; + Description = "Removes the scheduled job identified by the request, after stopping its execution cycle, if it has one."; + + RequestParam(r => r.ScheduledJobId, "The unique identifier of the scheduled job to remove. Required."); + + ExampleRequest = new RemoveScheduledJobRequest(ScheduledJobId: Guid.NewGuid()); + + Response(200, "The scheduled job was successfully removed.", example: new SuccessResponse(true)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpoint.cs new file mode 100644 index 00000000..cf09450c --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpoint.cs @@ -0,0 +1,138 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Lumina.Presentation.Web.Core.Themes; +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using Microsoft.Extensions.Options; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler; + +/// +/// API endpoint for the /{culture}/admin/scheduled-jobs route. +/// +public class SchedulerIndexViewEndpoint : BaseEndpoint +{ + // the resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it with the configured ResourcesPath + private const string VIEW_RESOURCE_BASE_NAME = "Lumina.Presentation.Web.Views.Admin.Scheduler"; + private const string VIEW_RESOURCE_LOCATION = "Lumina.Presentation.Web"; + // the page key mirrors the path of the Razor view under Core/Views, so that theme templates can override it at the page, section or default scope + private const string VIEW_PAGE_KEY = "admin/scheduler"; + + private readonly IAntiforgery _antiforgery; + private readonly IOptionsSnapshot _serverConfigurationOptions; + private readonly IUrlService _urlService; + private readonly ThemePageRenderer _themePageRenderer; + private readonly IStringLocalizer _localizer; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service used to create the anti forgery tokens of the page. + /// Injected options used to read the address of the API server that hosts the scheduled jobs hub. + /// Injected service for generating URLs from action and controller names, with localization. + /// Injected service for rendering themed pages. + /// Injected factory used to create the localizer of the view resources. + public SchedulerIndexViewEndpoint( + IAntiforgery antiforgery, + IOptionsSnapshot serverConfigurationOptions, + IUrlService urlService, + ThemePageRenderer themePageRenderer, + IStringLocalizerFactory stringLocalizerFactory) + { + _antiforgery = antiforgery; + _serverConfigurationOptions = serverConfigurationOptions; + _urlService = urlService; + _themePageRenderer = themePageRenderer; + _localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION); + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Scheduler.INDEX); + DontAutoTag(); + Options(options => options.WithTags("Admin")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + } + + /// + /// Displays the scheduled jobs dashboard, rendered by the active theme with a fallback to the Razor view. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + ServerConfigurationDto serverConfiguration = _serverConfigurationOptions.Value; + Dictionary localizedStrings = ThemePageDataFactory.CreateLocalizedStrings(_localizer); + + ThemePageDto pageModel = new() + { + PageKey = VIEW_PAGE_KEY, + Title = _localizer["ScheduledJobs"].Value, + Description = string.Empty, + PageData = new Dictionary + { + ["scheduledJobsHubUrl"] = $"{serverConfiguration.BaseAddress}:{serverConfiguration.Port}/scheduledJobsHub", + ["jobsListUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Scheduler.GET_SCHEDULED_JOBS) ?? string.Empty, + ["addJobUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Scheduler.ADD_SCHEDULED_JOB) ?? string.Empty, + ["historyUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Scheduler.GET_SCHEDULED_JOB_HISTORY) ?? string.Empty, + ["startJobUrlTemplate"] = _urlService.GetAbsoluteUrl(WebRoutes.Scheduler.START_SCHEDULED_JOB, new { scheduledJobId = default(System.Guid) }) ?? string.Empty, + ["stopJobUrlTemplate"] = _urlService.GetAbsoluteUrl(WebRoutes.Scheduler.STOP_SCHEDULED_JOB, new { scheduledJobId = default(System.Guid) }) ?? string.Empty, + ["fireJobUrlTemplate"] = _urlService.GetAbsoluteUrl(WebRoutes.Scheduler.FIRE_SCHEDULED_JOB, new { scheduledJobId = default(System.Guid) }) ?? string.Empty, + ["removeJobUrlTemplate"] = _urlService.GetAbsoluteUrl(WebRoutes.Scheduler.REMOVE_SCHEDULED_JOB, new { scheduledJobId = default(System.Guid) }) ?? string.Empty, + ["accessTokenUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Authentication.GET_API_ACCESS_TOKEN) ?? string.Empty, + ["getDisplayPreferencesUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Scheduler.GET_DISPLAY_PREFERENCES) ?? string.Empty, + ["updateDisplayPreferencesUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Scheduler.UPDATE_DISPLAY_PREFERENCES) ?? string.Empty, + ["antiforgeryToken"] = _antiforgery.GetAndStoreTokens(HttpContext).RequestToken ?? string.Empty, + ["strings"] = localizedStrings, + ["taskTypeNames"] = CreateSubgroup(localizedStrings, "TaskType", ["ScanMediaLibraries", "CleanTemporaryFiles", "RepairThemes", "CleanScheduledJobExecutionHistory"]), + ["statusNames"] = CreateSubgroup(localizedStrings, "Status", ["Added", "Active", "Running", "Completed"]) + } + }; + + Result sectionResult = await _themePageRenderer.RenderAsync(pageModel, requestedThemeId: null, cancellationToken).ConfigureAwait(false); + if (sectionResult.IsFailure) + return View("/Core/Views/Admin/Scheduler.cshtml"); + + return View( + "/Core/Views/Shared/_ThemedView.cshtml", + new ThemeViewDto(sectionResult.Value.Content, sectionResult.Value.Script), + new Dictionary { ["Title"] = pageModel.Title }); + } + + /// + /// Creates the subgroup of the localized strings whose resource names start with the provided prefix followed by a dot, + /// keyed by the remainder of their names, so that a template can resolve them with non dotted expressions. + /// + /// The localized strings keyed by their resource names. + /// The prefix of the resource names of the subgroup. + /// The names of the subgroup entries, without the prefix. + /// The localized strings of the subgroup keyed by their names. + private static IReadOnlyDictionary CreateSubgroup(IReadOnlyDictionary localizedStrings, string prefix, IReadOnlyList names) + { + Dictionary subgroup = new(StringComparer.OrdinalIgnoreCase); + foreach (string name in names) + if (localizedStrings.TryGetValue($"{prefix}.{name}", out object? value)) + subgroup[name] = value; + + return subgroup; + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointSummary.cs new file mode 100644 index 00000000..6fbd3034 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointSummary.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class SchedulerIndexViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public SchedulerIndexViewEndpointSummary() + { + Summary = "Renders the scheduled jobs dashboard view."; + Description = "Renders the view for managing the scheduled jobs and their execution cycle."; + + Response(200, "The view for managing the scheduled jobs and their execution cycle is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpoint.cs new file mode 100644 index 00000000..fa6988a2 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.StartScheduledJob; + +/// +/// API endpoint for the /{culture}/admin/api-scheduled-jobs/{scheduledJobId}/start route. +/// +public class StartScheduledJobEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public StartScheduledJobEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.PUT); + Routes(WebRoutes.Scheduler.START_SCHEDULED_JOB); + DontAutoTag(); + Options(options => options.WithTags("Admin")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + EnableAntiforgery(); + } + + /// + /// Starts the execution cycle of a scheduled job. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(StartScheduledJobRequest request, CancellationToken cancellationToken) + { + await _apiHttpClient.PutAsync(ApiRoutes.ScheduledJobs.START_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false); + return JsonSuccess(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointSummary.cs new file mode 100644 index 00000000..030d2f1a --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointSummary.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.StartScheduledJob; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class StartScheduledJobEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public StartScheduledJobEndpointSummary() + { + Summary = "Starts the execution cycle of a scheduled job."; + Description = "Starts the execution cycle of the scheduled job identified by the request, which runs its task once immediately and then on its schedule."; + + RequestParam(r => r.ScheduledJobId, "The unique identifier of the scheduled job whose execution cycle is started. Required."); + + ExampleRequest = new StartScheduledJobRequest(ScheduledJobId: Guid.NewGuid()); + + Response(200, "The execution cycle of the scheduled job was successfully started.", example: new SuccessResponse(true)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpoint.cs new file mode 100644 index 00000000..55616f57 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.StopScheduledJob; + +/// +/// API endpoint for the /{culture}/admin/api-scheduled-jobs/{scheduledJobId}/stop route. +/// +public class StopScheduledJobEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public StopScheduledJobEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.PUT); + Routes(WebRoutes.Scheduler.STOP_SCHEDULED_JOB); + DontAutoTag(); + Options(options => options.WithTags("Admin")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + EnableAntiforgery(); + } + + /// + /// Stops the execution cycle of a scheduled job. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(StopScheduledJobRequest request, CancellationToken cancellationToken) + { + await _apiHttpClient.PutAsync(ApiRoutes.ScheduledJobs.STOP_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false); + return JsonSuccess(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointSummary.cs new file mode 100644 index 00000000..53729520 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointSummary.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.StopScheduledJob; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class StopScheduledJobEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public StopScheduledJobEndpointSummary() + { + Summary = "Stops the execution cycle of a scheduled job."; + Description = "Stops the execution cycle of the scheduled job identified by the request, without removing it."; + + RequestParam(r => r.ScheduledJobId, "The unique identifier of the scheduled job whose execution cycle is stopped. Required."); + + ExampleRequest = new StopScheduledJobRequest(ScheduledJobId: Guid.NewGuid()); + + Response(200, "The execution cycle of the scheduled job was successfully stopped.", example: new SuccessResponse(true)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpoint.cs new file mode 100644 index 00000000..03075603 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.UpdateSchedulerDisplayPreferences; + +/// +/// API endpoint for the /{culture}/admin/api-scheduled-jobs/display-preferences route. +/// +public class UpdateSchedulerDisplayPreferencesEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public UpdateSchedulerDisplayPreferencesEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.PUT); + Routes(WebRoutes.Scheduler.UPDATE_DISPLAY_PREFERENCES); + DontAutoTag(); + Options(options => options.WithTags("Admin")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + EnableAntiforgery(); + } + + /// + /// Updates the display preferences of the scheduler page of the current user. + /// + /// The request containing the display preferences of the scheduler page of the current user. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(UpdateSchedulerDisplayPreferencesRequest request, CancellationToken cancellationToken) + { + await _apiHttpClient.PutAsync(ApiRoutes.ScheduledJobs.UPDATE_DISPLAY_PREFERENCES, request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointSummary.cs new file mode 100644 index 00000000..1a6e7038 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointSummary.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Enums.Scheduling; +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.UpdateSchedulerDisplayPreferences; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdateSchedulerDisplayPreferencesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateSchedulerDisplayPreferencesEndpointSummary() + { + Summary = "Updates the display preferences of the scheduler page."; + Description = "Stores the display preferences of the scheduler page of the current user, so that they are restored on every client the user signs in from."; + + RequestParam(r => r.JobTypeFilter, "The type of the scheduled job tasks whose executions are shown on the scheduler page, or null when all of them are shown."); + RequestParam(r => r.DisplayTimeSpan, "The time span, expressed in the display time unit, that the scheduler page shows. Required."); + RequestParam(r => r.DisplayTimeUnit, "The unit in which the displayed time span of the scheduler page is expressed. Required."); + + ExampleRequest = new UpdateSchedulerDisplayPreferencesRequest( + JobTypeFilter: ScheduledTaskType.ScanMediaLibraries, + DisplayTimeSpan: 10, + DisplayTimeUnit: SchedulerDisplayTimeUnit.Minutes + ); + + Response(200, "The display preferences of the scheduler page were successfully updated.", example: new SuccessResponse(true)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/GetApiAccessToken/GetApiAccessTokenEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/GetApiAccessToken/GetApiAccessTokenEndpoint.cs new file mode 100644 index 00000000..7c1d0e0d --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/GetApiAccessToken/GetApiAccessTokenEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.GetApiAccessToken; + +/// +/// API endpoint for the /{culture}/auth/api-access-token route. +/// +public class GetApiAccessTokenEndpoint : BaseEndpoint +{ + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Authentication.GET_API_ACCESS_TOKEN); + DontAutoTag(); + Options(options => options.WithTags("Authentication")); + } + + /// + /// Gets the API access token of the current user, used to authenticate the real time SignalR connections of the current page. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // The response carries a credential, so it must never be cached by the browser or by any intermediary. + HttpContext.Response.Headers.CacheControl = "no-store"; + HttpContext.Response.Headers.Pragma = "no-cache"; + + if (User.Identity?.IsAuthenticated is not true) + return Task.FromResult(Results.Problem( + statusCode: StatusCodes.Status401Unauthorized, + title: "Unauthorized", + detail: "You are not authorized")); + + string? token = User.FindFirst("Token")?.Value; + if (string.IsNullOrEmpty(token)) + return Task.FromResult(Results.Problem( + statusCode: StatusCodes.Status401Unauthorized, + title: "Unauthorized", + detail: "The API access token of the current user is not available")); + + return Task.FromResult(JsonSuccess(new { token })); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/GetApiAccessToken/GetApiAccessTokenEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/GetApiAccessToken/GetApiAccessTokenEndpointSummary.cs new file mode 100644 index 00000000..943fb9ec --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/GetApiAccessToken/GetApiAccessTokenEndpointSummary.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.GetApiAccessToken; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetApiAccessTokenEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetApiAccessTokenEndpointSummary() + { + Summary = "Gets the API access token of the current user."; + Description = "Gets the API access token of the current user, used to authenticate the real time SignalR connections of the current page."; + + Response(200, "The API access token of the current user is returned.", + example: new + { + success = true, + data = new + { + token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIn0.example" + } + }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ar-SA.resx index df7a2beb..d97d0d13 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ar-SA.resx @@ -738,4 +738,46 @@ تعذّرت قراءة أرشيف المكوّن الإضافي المرفوع! + + لم يتم العثور على المهمة المجدولة! + + + لا يمكن أن يكون اسم المهمة المجدولة فارغاً! + + + يجب أن تكون دقائق الفاصل رقماً موجباً! + + + يجب أن تكون الساعة بين 0 و 23! + + + يجب أن تكون الدقيقة بين 0 و 59! + + + المهمة المجدولة بهذا الاسم موجودة بالفعل! + + + تنفيذ المهمة المجدولة موجود بالفعل! + + + لم يتم العثور على تنفيذ المهمة المجدولة! + + + تم بدء دورة تنفيذ المهمة المجدولة بالفعل! + + + لم يتم بدء دورة تنفيذ المهمة المجدولة! + + + المهمة المجدولة قيد التشغيل بالفعل! + + + يمكن إكمال المهمة المجدولة قيد التشغيل فقط! + + + يجب أن تكون الفترة الزمنية للعرض في صفحة الجدولة رقمًا موجبًا! + + + نوع الجدول غير صالح! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx index 98c4b350..8f3f3fb6 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx @@ -738,4 +738,46 @@ Das hochgeladene Plugin-Archiv konnte nicht gelesen werden! + + Der geplante Auftrag wurde nicht gefunden! + + + Der Name des geplanten Auftrags darf nicht leer sein! + + + Die Intervallminuten müssen eine positive Zahl sein! + + + Die Stunde muss zwischen 0 und 23 liegen! + + + Die Minute muss zwischen 0 und 59 liegen! + + + Ein geplanter Auftrag mit diesem Namen ist bereits vorhanden! + + + Die Ausführung des geplanten Auftrags existiert bereits! + + + Die Ausführung des geplanten Auftrags wurde nicht gefunden! + + + Der Ausführungszyklus des geplanten Auftrags wurde bereits gestartet! + + + Der Ausführungszyklus des geplanten Auftrags wurde nicht gestartet! + + + Der geplante Auftrag wird bereits ausgeführt! + + + Nur ein laufender geplanter Auftrag kann abgeschlossen werden! + + + Der Anzeigezeitraum der Scheduler-Seite muss eine positive Zahl sein! + + + Der Zeitplantyp ist ungültig! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx index d3bb66b1..326d2996 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx @@ -738,4 +738,46 @@ The plugin archive could not be read! + + The scheduled job was not found! + + + The name of the scheduled job cannot be empty! + + + The interval minutes must be a positive number! + + + The hour must be between 0 and 23! + + + The minute must be between 0 and 59! + + + A scheduled job with this name already exists! + + + The execution of the scheduled job already exists! + + + The execution of the scheduled job was not found! + + + The execution cycle of the scheduled job has already been started! + + + The execution cycle of the scheduled job has not been started! + + + The scheduled job is already running! + + + Only a running scheduled job can be completed! + + + The display time span of the scheduler page must be a positive number! + + + The schedule type is invalid! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx index 5e32bd3f..a6e0c2e8 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx @@ -738,4 +738,46 @@ No se pudo leer el archivo del plugin subido! + + La tarea programada no fue encontrada! + + + El nombre de la tarea programada no puede estar vacío! + + + Los minutos del intervalo deben ser un número positivo! + + + La hora debe estar entre 0 y 23! + + + El minuto debe estar entre 0 y 59! + + + Ya existe una tarea programada con este nombre! + + + La ejecución de la tarea programada ya existe! + + + No se encontró la ejecución de la tarea programada! + + + El ciclo de ejecución de la tarea programada ya se ha iniciado! + + + El ciclo de ejecución de la tarea programada no se ha iniciado! + + + La tarea programada ya se está ejecutando! + + + Solo se puede completar una tarea programada en ejecución! + + + El intervalo de visualización de la página de tareas programadas debe ser un número positivo! + + + El tipo de programación no es válido! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx index a58eb427..734e8420 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx @@ -738,4 +738,46 @@ L'archive du plugin téléversé n a pas pu être lue ! + + Le travail planifié est introuvable ! + + + Le nom du travail planifié ne peut pas être vide ! + + + Les minutes de l'intervalle doivent être un nombre positif ! + + + L'heure doit être comprise entre 0 et 23 ! + + + La minute doit être comprise entre 0 et 59 ! + + + Un travail planifié portant ce nom existe déjà ! + + + L'exécution du travail planifié existe déjà ! + + + L'exécution du travail planifié est introuvable ! + + + Le cycle d'exécution du travail planifié a déjà été démarré ! + + + Le cycle d'exécution du travail planifié n'a pas été démarré ! + + + Le travail planifié est déjà en cours d'exécution ! + + + Seul un travail planifié en cours d'exécution peut être terminé ! + + + La durée d'affichage de la page des travaux planifiés doit être un nombre positif ! + + + Le type de planification n'est pas valide ! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx index 3215f06e..d29f703f 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx @@ -738,4 +738,46 @@ Non è stato possibile leggere l archivio del plugin caricato! + + Il processo pianificato non è stato trovato! + + + Il nome del processo pianificato non può essere vuoto! + + + I minuti dell'intervallo devono essere un numero positivo! + + + L'ora deve essere compresa tra 0 e 23! + + + Il minuto deve essere compreso tra 0 e 59! + + + Esiste già un processo pianificato con questo nome! + + + L'esecuzione del processo pianificato esiste già! + + + L'esecuzione del processo pianificato non è stata trovata! + + + Il ciclo di esecuzione del processo pianificato è già stato avviato! + + + Il ciclo di esecuzione del processo pianificato non è stato avviato! + + + Il processo pianificato è già in esecuzione! + + + Solo un processo pianificato in esecuzione può essere completato! + + + L'intervallo di visualizzazione della pagina dei processi pianificati deve essere un numero positivo! + + + Il tipo di pianificazione non è valido! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx index f939e5e6..811c5865 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx @@ -738,4 +738,46 @@ アップロードされたプラグインアーカイブを読み取れませんでした! + + スケジュールされたジョブが見つかりません! + + + スケジュールされたジョブの名前を空にすることはできません! + + + 間隔の分数は正の数である必要があります! + + + 時間は0から23の間である必要があります! + + + 分は0から59の間である必要があります! + + + この名前のスケジュールされたジョブは既に存在します! + + + スケジュールされたジョブの実行は既に存在します! + + + スケジュールされたジョブの実行が見つかりません! + + + スケジュールされたジョブの実行サイクルは既に開始されています! + + + スケジュールされたジョブの実行サイクルは開始されていません! + + + スケジュールされたジョブは既に実行中です! + + + 実行中のスケジュールされたジョブのみ完了できます! + + + スケジューラーページの表示期間は正の数である必要があります! + + + スケジュールタイプが無効です! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx index a7e57816..7dc35049 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx @@ -738,4 +738,46 @@ The plugin archive could not be read! + + The scheduled job was not found! + + + The name of the scheduled job cannot be empty! + + + The interval minutes must be a positive number! + + + The hour must be between 0 and 23! + + + The minute must be between 0 and 59! + + + A scheduled job with this name already exists! + + + The execution of the scheduled job already exists! + + + The execution of the scheduled job was not found! + + + The execution cycle of the scheduled job has already been started! + + + The execution cycle of the scheduled job has not been started! + + + The scheduled job is already running! + + + Only a running scheduled job can be completed! + + + The display time span of the scheduler page must be a positive number! + + + The schedule type is invalid! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx index c4566870..c4dd1bc3 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx @@ -738,4 +738,46 @@ Arhiva pluginului încărcat nu a putut fi citită! + + Jobul programat nu a fost găsit! + + + Numele jobului programat nu poate fi gol! + + + Minutele intervalului trebuie să fie un număr pozitiv! + + + Ora trebuie să fie între 0 și 23! + + + Minutul trebuie să fie între 0 și 59! + + + Există deja un job programat cu acest nume! + + + Execuția jobului programat există deja! + + + Execuția jobului programat nu a fost găsită! + + + Ciclul de execuție al jobului programat a fost deja pornit! + + + Ciclul de execuție al jobului programat nu a fost pornit! + + + Jobul programat rulează deja! + + + Doar un job programat în execuție poate fi finalizat! + + + Durata de afișare a paginii joburilor programate trebuie să fie un număr pozitiv! + + + Tipul de programare este invalid! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.uk-UA.resx index 1a7a32aa..20b6d57d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.uk-UA.resx @@ -738,4 +738,46 @@ Не вдалося прочитати архів завантаженого плагіна! + + Плановане завдання не знайдено! + + + Назва планованого завдання не може бути порожньою! + + + Хвилини інтервалу повинні бути додатним числом! + + + Година повинна бути між 0 та 23! + + + Хвилина повинна бути між 0 та 59! + + + Плановане завдання з таким ім'ям вже існує! + + + Виконання планованого завдання вже існує! + + + Виконання планованого завдання не знайдено! + + + Цикл виконання планованого завдання вже запущено! + + + Цикл виконання планованого завдання не запущено! + + + Плановане завдання вже виконується! + + + Завершити можна лише плановане завдання, що виконується! + + + Період відображення сторінки планувальника має бути додатним числом! + + + Тип розкладу недійсний! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx index 3426da90..818ffca4 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx @@ -738,4 +738,46 @@ 无法读取上传的插件存档! + + 未找到计划任务! + + + 计划任务的名称不能为空! + + + 间隔分钟必须为正数! + + + 小时必须在0到23之间! + + + 分钟必须在0到59之间! + + + 已存在同名计划任务! + + + 计划任务的执行记录已存在! + + + 未找到计划任务的执行记录! + + + 计划任务的执行周期已启动! + + + 计划任务的执行周期尚未启动! + + + 计划任务已在运行! + + + 只有运行中的计划任务才能完成! + + + 计划任务页面的显示时长必须是正数! + + + 调度类型无效! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ar-SA.resx new file mode 100644 index 00000000..8cd2978e --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ar-SA.resx @@ -0,0 +1,171 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + المهام المجدولة + + + تصفية حسب نوع المهمة + + + الكل + + + فحص مكتبات الوسائط + + + تنظيف الملفات المؤقتة + + + عرض آخر + + + وحدة الوقت + + + دقائق + + + دقيقة + + + ساعات + + + أيام + + + تحديث + + + المهام الحالية + + + إضافة مهمة + + + المعرّف + + + الاسم + + + نوع المهمة + + + نوع الجدولة + + + الفاصل الزمني + + + الوقت + + + الحالة + + + بدأت + + + اكتملت + + + الإجراءات + + + اسم المهمة + + + فاصل زمني + + + يومي + + + الفاصل الزمني (دقائق) + + + الساعة + + + الدقيقة + + + إضافة مهمة + + + بدء + + + إيقاف + + + تنفيذ + + + إزالة + + + لم تتم إضافة مهام + + + تم بدء المهمة بنجاح. + + + تم إيقاف المهمة بنجاح. + + + تم تنفيذ المهمة بنجاح. + + + تمت إضافة المهمة بنجاح. + + + تمت إزالة المهمة بنجاح. + + + لم يتم العثور على المهمة. + + + المهمة قيد التشغيل بالفعل. + + + مضافة + + + نشطة + + + قيد التشغيل + + + مكتملة + + + هل تريد إزالة هذه المهمة المجدولة؟ + + + اسم المهمة مطلوب. + + + إصلاح السمات + + + تنظيف سجل الوظائف + + + عند بدء التشغيل + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.de-DE.resx new file mode 100644 index 00000000..6caf3884 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.de-DE.resx @@ -0,0 +1,171 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Geplante Aufgaben + + + Nach Aufgabentyp filtern + + + Alle + + + Medienbibliotheken scannen + + + Temporäre Dateien bereinigen + + + Zuletzt anzeigen + + + Zeiteinheit + + + Minuten + + + Min. + + + Stunden + + + Tage + + + Aktualisieren + + + Aktuelle Aufgaben + + + Neue Aufgabe hinzufügen + + + ID + + + Name + + + Aufgabentyp + + + Zeitplantyp + + + Intervall + + + Uhrzeit + + + Status + + + Gestartet + + + Abgeschlossen + + + Aktionen + + + Aufgabenname + + + Intervall + + + Täglich + + + Intervall (Minuten) + + + Stunde + + + Minute + + + Aufgabe hinzufügen + + + Starten + + + Stoppen + + + Ausführen + + + Entfernen + + + Keine Aufgaben hinzugefügt + + + Aufgabe erfolgreich gestartet. + + + Aufgabe erfolgreich gestoppt. + + + Aufgabe erfolgreich ausgeführt. + + + Aufgabe erfolgreich hinzugefügt. + + + Aufgabe erfolgreich entfernt. + + + Aufgabe nicht gefunden. + + + Die Aufgabe läuft bereits. + + + Hinzugefügt + + + Aktiv + + + Läuft + + + Abgeschlossen + + + Diese geplante Aufgabe entfernen? + + + Der Aufgabenname ist erforderlich. + + + Designs reparieren + + + Jobverlauf bereinigen + + + Beim Start + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.en-US.resx new file mode 100644 index 00000000..24fa61bb --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.en-US.resx @@ -0,0 +1,171 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Scheduled jobs + + + Filter by job type + + + All + + + Scan media libraries + + + Clean temporary files + + + Display last + + + Time unit + + + Minutes + + + min + + + Hours + + + Days + + + Update + + + Current jobs + + + Add new job + + + Id + + + Name + + + Job type + + + Schedule type + + + Interval + + + Time + + + Status + + + Started + + + Completed + + + Actions + + + Job name + + + Interval + + + Daily + + + Interval (minutes) + + + Hour + + + Minute + + + Add job + + + Start + + + Stop + + + Fire + + + Remove + + + No jobs added + + + Job started successfully. + + + Job stopped successfully. + + + Job fired successfully. + + + Job added successfully. + + + Job removed successfully. + + + Job not found. + + + The job is already running. + + + Added + + + Active + + + Running + + + Completed + + + Remove this scheduled job? + + + The job name is required. + + + Repair themes + + + Clean job history + + + At startup + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.es-ES.resx new file mode 100644 index 00000000..0a45962c --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.es-ES.resx @@ -0,0 +1,171 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Tareas programadas + + + Filtrar por tipo de tarea + + + Todas + + + Analizar bibliotecas multimedia + + + Limpiar archivos temporales + + + Mostrar las últimas + + + Unidad de tiempo + + + Minutos + + + min + + + Horas + + + Días + + + Actualizar + + + Tareas actuales + + + Añadir tarea + + + Id + + + Nombre + + + Tipo de tarea + + + Tipo de programación + + + Intervalo + + + Hora + + + Estado + + + Iniciado + + + Completado + + + Acciones + + + Nombre de la tarea + + + Intervalo + + + Diaria + + + Intervalo (minutos) + + + Hora + + + Minuto + + + Añadir tarea + + + Iniciar + + + Detener + + + Ejecutar + + + Eliminar + + + No hay tareas añadidas + + + La tarea se inició correctamente. + + + La tarea se detuvo correctamente. + + + La tarea se ejecutó correctamente. + + + La tarea se añadió correctamente. + + + La tarea se eliminó correctamente. + + + Tarea no encontrada. + + + La tarea ya está en ejecución. + + + Añadida + + + Activa + + + En ejecución + + + Completada + + + ¿Eliminar esta tarea programada? + + + El nombre de la tarea es obligatorio. + + + Reparar temas + + + Limpiar historial de trabajos + + + Al inicio + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.fr-FR.resx new file mode 100644 index 00000000..bc2a145d --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.fr-FR.resx @@ -0,0 +1,171 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Tâches planifiées + + + Filtrer par type de tâche + + + Toutes + + + Analyser les médiathèques + + + Nettoyer les fichiers temporaires + + + Afficher les dernières + + + Unité de temps + + + Minutes + + + min + + + Heures + + + Jours + + + Mettre à jour + + + Tâches en cours + + + Ajouter une tâche + + + Id + + + Nom + + + Type de tâche + + + Type de planification + + + Intervalle + + + Heure + + + Statut + + + Démarrage + + + Terminé + + + Actions + + + Nom de la tâche + + + Intervalle + + + Quotidien + + + Intervalle (minutes) + + + Heure + + + Minute + + + Ajouter la tâche + + + Démarrer + + + Arrêter + + + Exécuter + + + Supprimer + + + Aucune tâche ajoutée + + + La tâche a démarré avec succès. + + + La tâche a été arrêtée avec succès. + + + La tâche a été exécutée avec succès. + + + La tâche a été ajoutée avec succès. + + + La tâche a été supprimée avec succès. + + + Tâche introuvable. + + + La tâche est déjà en cours d'exécution. + + + Ajoutée + + + Active + + + En cours + + + Terminée + + + Supprimer cette tâche planifiée ? + + + Le nom de la tâche est requis. + + + Réparer les thèmes + + + Nettoyer l'historique des tâches + + + Au démarrage + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.it-IT.resx new file mode 100644 index 00000000..bc5520f8 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.it-IT.resx @@ -0,0 +1,171 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Attività pianificate + + + Filtra per tipo di attività + + + Tutte + + + Analizza le librerie multimediali + + + Pulisci i file temporanei + + + Mostra ultime + + + Unità di tempo + + + Minuti + + + min + + + Ore + + + Giorni + + + Aggiorna + + + Attività correnti + + + Aggiungi attività + + + Id + + + Nome + + + Tipo di attività + + + Tipo di pianificazione + + + Intervallo + + + Ora + + + Stato + + + Avviato + + + Completato + + + Azioni + + + Nome attività + + + Intervallo + + + Giornaliera + + + Intervallo (minuti) + + + Ora + + + Minuto + + + Aggiungi attività + + + Avvia + + + Ferma + + + Esegui + + + Rimuovi + + + Nessuna attività aggiunta + + + Attività avviata correttamente. + + + Attività fermata correttamente. + + + Attività eseguita correttamente. + + + Attività aggiunta correttamente. + + + Attività rimossa correttamente. + + + Attività non trovata. + + + L'attività è già in esecuzione. + + + Aggiunta + + + Attiva + + + In esecuzione + + + Completata + + + Rimuovere questa attività pianificata? + + + Il nome dell'attività è obbligatorio. + + + Ripara i temi + + + Pulisci la cronologia dei processi + + + All'avvio + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ja-JP.resx new file mode 100644 index 00000000..efe836d0 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ja-JP.resx @@ -0,0 +1,171 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + スケジュール済みジョブ + + + ジョブの種類で絞り込む + + + すべて + + + メディアライブラリをスキャン + + + 一時ファイルをクリーンアップ + + + 表示する範囲 + + + 時間の単位 + + + 分 + + + 分 + + + 時間 + + + 日 + + + 更新 + + + 現在のジョブ + + + 新しいジョブを追加 + + + ID + + + 名前 + + + ジョブの種類 + + + スケジュールの種類 + + + 間隔 + + + 時刻 + + + 状態 + + + 開始 + + + 完了 + + + 操作 + + + ジョブ名 + + + 間隔 + + + 毎日 + + + 間隔(分) + + + 時 + + + 分 + + + ジョブを追加 + + + 開始 + + + 停止 + + + 実行 + + + 削除 + + + ジョブがありません + + + ジョブが正常に開始されました。 + + + ジョブが正常に停止されました。 + + + ジョブが正常に実行されました。 + + + ジョブが正常に追加されました。 + + + ジョブが正常に削除されました。 + + + ジョブが見つかりません。 + + + ジョブはすでに実行中です。 + + + 追加済み + + + アクティブ + + + 実行中 + + + 完了 + + + このスケジュール済みジョブを削除しますか? + + + ジョブ名が必要です。 + + + テーマを修復 + + + ジョブ履歴を削除 + + + 起動時 + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.resx new file mode 100644 index 00000000..24fa61bb --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.resx @@ -0,0 +1,171 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Scheduled jobs + + + Filter by job type + + + All + + + Scan media libraries + + + Clean temporary files + + + Display last + + + Time unit + + + Minutes + + + min + + + Hours + + + Days + + + Update + + + Current jobs + + + Add new job + + + Id + + + Name + + + Job type + + + Schedule type + + + Interval + + + Time + + + Status + + + Started + + + Completed + + + Actions + + + Job name + + + Interval + + + Daily + + + Interval (minutes) + + + Hour + + + Minute + + + Add job + + + Start + + + Stop + + + Fire + + + Remove + + + No jobs added + + + Job started successfully. + + + Job stopped successfully. + + + Job fired successfully. + + + Job added successfully. + + + Job removed successfully. + + + Job not found. + + + The job is already running. + + + Added + + + Active + + + Running + + + Completed + + + Remove this scheduled job? + + + The job name is required. + + + Repair themes + + + Clean job history + + + At startup + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ro-RO.resx new file mode 100644 index 00000000..abd5a9b4 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ro-RO.resx @@ -0,0 +1,171 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Sarcini programate + + + Filtrează după tipul de sarcină + + + Toate + + + Scanează bibliotecile media + + + Curăță fișierele temporare + + + Afișează ultimele + + + Unitate de timp + + + Minute + + + min + + + Ore + + + Zile + + + Actualizează + + + Sarcini curente + + + Adaugă sarcină + + + Id + + + Nume + + + Tip de sarcină + + + Tip de programare + + + Interval + + + Ora + + + Stare + + + Începută + + + Finalizată + + + Acțiuni + + + Numele sarcinii + + + Interval + + + Zilnic + + + Interval (minute) + + + Oră + + + Minut + + + Adaugă sarcină + + + Pornește + + + Oprește + + + Execută + + + Elimină + + + Nicio sarcină adăugată + + + Sarcina a fost pornită cu succes. + + + Sarcina a fost oprită cu succes. + + + Sarcina a fost executată cu succes. + + + Sarcina a fost adăugată cu succes. + + + Sarcina a fost eliminată cu succes. + + + Sarcina nu a fost găsită. + + + Sarcina rulează deja. + + + Adăugată + + + Activă + + + În execuție + + + Finalizată + + + Elimini această sarcină programată? + + + Numele sarcinii este obligatoriu. + + + Repară temele + + + Curăță istoricul proceselor + + + La pornire + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.uk-UA.resx new file mode 100644 index 00000000..1feacdb6 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.uk-UA.resx @@ -0,0 +1,171 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Заплановані завдання + + + Фільтрувати за типом завдання + + + Усі + + + Сканувати медіатеки + + + Очистити тимчасові файли + + + Показати останні + + + Одиниця часу + + + Хвилини + + + хв + + + Години + + + Дні + + + Оновити + + + Поточні завдання + + + Додати завдання + + + Id + + + Назва + + + Тип завдання + + + Тип розкладу + + + Інтервал + + + Час + + + Статус + + + Запущено + + + Завершено + + + Дії + + + Назва завдання + + + Інтервал + + + Щоденно + + + Інтервал (хвилини) + + + Година + + + Хвилина + + + Додати завдання + + + Запустити + + + Зупинити + + + Виконати + + + Видалити + + + Завдань не додано + + + Завдання успішно запущено. + + + Завдання успішно зупинено. + + + Завдання успішно виконано. + + + Завдання успішно додано. + + + Завдання успішно видалено. + + + Завдання не знайдено. + + + Завдання вже виконується. + + + Додано + + + Активне + + + Виконується + + + Завершено + + + Видалити це заплановане завдання? + + + Назва завдання обов'язкова. + + + Відновлення тем + + + Очистити історію завдань + + + Під час запуску + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.zh-CN.resx new file mode 100644 index 00000000..8aed079b --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.zh-CN.resx @@ -0,0 +1,171 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 计划任务 + + + 按任务类型筛选 + + + 全部 + + + 扫描媒体库 + + + 清理临时文件 + + + 显示最近 + + + 时间单位 + + + 分钟 + + + 分 + + + 小时 + + + 天 + + + 更新 + + + 当前任务 + + + 添加新任务 + + + ID + + + 名称 + + + 任务类型 + + + 计划类型 + + + 间隔 + + + 时间 + + + 状态 + + + 已开始 + + + 已完成 + + + 操作 + + + 任务名称 + + + 间隔 + + + 每日 + + + 间隔(分钟) + + + 小时 + + + 分钟 + + + 添加任务 + + + 开始 + + + 停止 + + + 执行 + + + 删除 + + + 尚未添加任务 + + + 任务已成功开始。 + + + 任务已成功停止。 + + + 任务已成功执行。 + + + 任务已成功添加。 + + + 任务已成功删除。 + + + 找不到任务。 + + + 任务已在运行中。 + + + 已添加 + + + 活动中 + + + 运行中 + + + 已完成 + + + 删除此计划任务? + + + 需要提供任务名称。 + + + 修复主题 + + + 清理作业历史 + + + 启动时 + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ar-SA.resx index 429aaf7b..021c346f 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ar-SA.resx @@ -1,4 +1,4 @@ - + + +} diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml index d7fdaafa..912eed53 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml @@ -8,7 +8,7 @@ @using System.Security.Claims @{ - // generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler + // Generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler. var scriptId = ScriptIdentifierHelper.GenerateScriptId(); } @@ -162,7 +162,7 @@ @section Scripts { ")] // script injection + public async Task AddScheduledJob_WithMaliciousName_ShouldNotLeakDataOrExecuteInjection(string maliciousName) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + _adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + object requestBody = new + { + Name = maliciousName, + TaskType = ScheduledTaskType.ScanMediaLibraries, + ScheduleType = ScheduleType.WithIntervalInMinutes, + IntervalMinutes = 60 + }; + + // Act + HttpResponseMessage response = await client.PostAsJsonAsync("/api/v1/scheduled-jobs", requestBody); + + // Assert + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + // The malicious name either reaches the parameterized insert verbatim or is rejected by validation; it never corrupts the storage medium. + Assert.True(response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.UnprocessableEntity); + + if (response.StatusCode == HttpStatusCode.OK) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.NotNull(await dbContext.ScheduledJobs.FirstOrDefaultAsync(scheduledJob => scheduledJob.Name == maliciousName)); + } + } + + /// + /// Disposes API factory resources. + /// + public async ValueTask DisposeAsync() + { + if (_adminUserId != Guid.Empty) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + ScheduledJobEntity[] scheduledJobs = await dbContext.ScheduledJobs + .Where(scheduledJob => scheduledJob.OwnerUserId == _adminUserId) + .ToArrayAsync(); + foreach (ScheduledJobEntity scheduledJob in scheduledJobs) + { + dbContext.ScheduledJobExecutions.RemoveRange(dbContext.ScheduledJobExecutions.Where(execution => execution.ScheduledJobId == scheduledJob.Id)); + dbContext.ScheduledJobs.Remove(scheduledJob); + } + await dbContext.SaveChangesAsync(); + + await _apiFactory.RemoveAdminUserAsync(_adminUserId); + } + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointTests.cs new file mode 100644 index 00000000..1cc4b2f0 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointTests.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler.AddScheduledJob; + +/// +/// Contains security tests for the /{culture}/admin/api-scheduled-jobs/add route served by the class. +/// +[ExcludeFromCodeCoverage] +public class AddScheduledJobEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public AddScheduledJobEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task AddScheduledJob_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + string url = "/en-us/admin/api-scheduled-jobs/add"; + HttpRequestMessage request = new(HttpMethod.Post, url) + { + Content = CreateJsonContent() + }; + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint.StartsWith("scheduled-jobs", StringComparison.Ordinal)); + } + + [Fact] + public async Task AddScheduledJob_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + string url = "/en-us/admin/api-scheduled-jobs/add"; + HttpRequestMessage request = new(HttpMethod.Post, url) + { + Content = CreateJsonContent() + }; + request.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint.StartsWith("scheduled-jobs", StringComparison.Ordinal)); + } + + /// + /// Creates the empty JSON body of the request; the content type is set without the charset suffix, because the antiforgery middleware matches the content type exactly. + /// + /// The created content. + private static StringContent CreateJsonContent() + { + StringContent content = new("{}", Encoding.UTF8, "application/json"); + content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + return content; + } +} \ No newline at end of file diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs new file mode 100644 index 00000000..9a81a979 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler.FireScheduledJob; + +/// +/// Contains security tests for the /{culture}/admin/api-scheduled-jobs/{scheduledJobId}/fire route served by the class. +/// +[ExcludeFromCodeCoverage] +public class FireScheduledJobEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public FireScheduledJobEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task FireScheduledJob_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + string url = $"/en-us/admin/api-scheduled-jobs/{Guid.NewGuid()}/fire"; + HttpRequestMessage request = new(HttpMethod.Put, url) + { + Content = CreateJsonContent() + }; + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint.StartsWith("scheduled-jobs", StringComparison.Ordinal)); + } + + [Fact] + public async Task FireScheduledJob_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + string url = $"/en-us/admin/api-scheduled-jobs/{Guid.NewGuid()}/fire"; + HttpRequestMessage request = new(HttpMethod.Put, url) + { + Content = CreateJsonContent() + }; + request.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint.StartsWith("scheduled-jobs", StringComparison.Ordinal)); + } + + /// + /// Creates the empty JSON body of the request; the content type is set without the charset suffix, because the antiforgery middleware matches the content type exactly. + /// + /// The created content. + private static StringContent CreateJsonContent() + { + StringContent content = new("{}", Encoding.UTF8, "application/json"); + content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + return content; + } +} \ No newline at end of file diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs new file mode 100644 index 00000000..8c543f07 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs @@ -0,0 +1,87 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.GetScheduledJobHistory; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler.GetScheduledJobHistory; + +/// +/// Contains security tests for the /{culture}/admin/api-scheduled-jobs/history route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetScheduledJobHistoryEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly ScheduledJobExecutionDtoFixture _scheduledJobExecutionDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetScheduledJobHistoryEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetScheduledJobHistory_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/admin/api-scheduled-jobs/history"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("auth/login", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetScheduledJobHistory_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-scheduled-jobs/history"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetScheduledJobHistory_WhenCalledByAdminUser_ShouldReturnExecutionHistoryData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + ScheduledJobExecutionDto[] expectedExecutions = [.. _scheduledJobExecutionDtoFixture.CreateMany(2)]; + _apiFactory.ApiClientStub.RegisterGetResponse("scheduled-jobs/history", expectedExecutions); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/admin/api-scheduled-jobs/history"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointTests.cs new file mode 100644 index 00000000..3dcb9a45 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointTests.cs @@ -0,0 +1,87 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.GetScheduledJobs; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler.GetScheduledJobs; + +/// +/// Contains security tests for the /{culture}/admin/api-scheduled-jobs route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetScheduledJobsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly ScheduledJobDtoFixture _scheduledJobDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetScheduledJobsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetScheduledJobs_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/admin/api-scheduled-jobs"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("auth/login", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetScheduledJobs_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-scheduled-jobs"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetScheduledJobs_WhenCalledByAdminUser_ShouldReturnScheduledJobsData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + ScheduledJobDto[] expectedJobs = [.. _scheduledJobDtoFixture.CreateMany(2)]; + _apiFactory.ApiClientStub.RegisterGetResponse("scheduled-jobs", expectedJobs); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/admin/api-scheduled-jobs"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs new file mode 100644 index 00000000..79a4fc7e --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs @@ -0,0 +1,87 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.GetSchedulerDisplayPreferences; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler.GetSchedulerDisplayPreferences; + +/// +/// Contains security tests for the /{culture}/admin/api-scheduled-jobs/display-preferences route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetSchedulerDisplayPreferencesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly SchedulerDisplayPreferencesDtoFixture _schedulerDisplayPreferencesDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetSchedulerDisplayPreferencesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetSchedulerDisplayPreferences_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/admin/api-scheduled-jobs/display-preferences"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("auth/login", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetSchedulerDisplayPreferences_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-scheduled-jobs/display-preferences"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetSchedulerDisplayPreferences_WhenCalledByAdminUser_ShouldReturnDisplayPreferencesData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + SchedulerDisplayPreferencesDto expectedPreferences = _schedulerDisplayPreferencesDtoFixture.Create(); + _apiFactory.ApiClientStub.RegisterGetResponse("scheduled-jobs/display-preferences", expectedPreferences); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/admin/api-scheduled-jobs/display-preferences"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs new file mode 100644 index 00000000..576f7881 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler.RemoveScheduledJob; + +/// +/// Contains security tests for the /{culture}/admin/api-scheduled-jobs/{scheduledJobId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class RemoveScheduledJobEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RemoveScheduledJobEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task RemoveScheduledJob_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + string url = $"/en-us/admin/api-scheduled-jobs/{Guid.NewGuid()}"; + HttpRequestMessage request = new(HttpMethod.Delete, url) + { + Content = CreateJsonContent() + }; + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint.StartsWith("scheduled-jobs", StringComparison.Ordinal)); + } + + [Fact] + public async Task RemoveScheduledJob_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + string url = $"/en-us/admin/api-scheduled-jobs/{Guid.NewGuid()}"; + HttpRequestMessage request = new(HttpMethod.Delete, url) + { + Content = CreateJsonContent() + }; + request.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint.StartsWith("scheduled-jobs", StringComparison.Ordinal)); + } + + /// + /// Creates the empty JSON body of the request; the content type is set without the charset suffix, because the antiforgery middleware matches the content type exactly. + /// + /// The created content. + private static StringContent CreateJsonContent() + { + StringContent content = new("{}", Encoding.UTF8, "application/json"); + content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + return content; + } +} \ No newline at end of file diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointTests.cs new file mode 100644 index 00000000..be0107a6 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler; + +/// +/// Contains security tests for the /{culture}/admin/scheduled-jobs route served by the class. +/// +[ExcludeFromCodeCoverage] +public class SchedulerIndexViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public SchedulerIndexViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task SchedulerIndex_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/admin/scheduled-jobs"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("auth/login", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task SchedulerIndex_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/scheduled-jobs"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task SchedulerIndex_WhenCalledByAdminUser_ShouldReturnSchedulerPage() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/scheduled-jobs"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs new file mode 100644 index 00000000..99bdf02f --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler.StartScheduledJob; + +/// +/// Contains security tests for the /{culture}/admin/api-scheduled-jobs/{scheduledJobId}/start route served by the class. +/// +[ExcludeFromCodeCoverage] +public class StartScheduledJobEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public StartScheduledJobEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task StartScheduledJob_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + string url = $"/en-us/admin/api-scheduled-jobs/{Guid.NewGuid()}/start"; + HttpRequestMessage request = new(HttpMethod.Put, url) + { + Content = CreateJsonContent() + }; + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint.StartsWith("scheduled-jobs", StringComparison.Ordinal)); + } + + [Fact] + public async Task StartScheduledJob_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + string url = $"/en-us/admin/api-scheduled-jobs/{Guid.NewGuid()}/start"; + HttpRequestMessage request = new(HttpMethod.Put, url) + { + Content = CreateJsonContent() + }; + request.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint.StartsWith("scheduled-jobs", StringComparison.Ordinal)); + } + + /// + /// Creates the empty JSON body of the request; the content type is set without the charset suffix, because the antiforgery middleware matches the content type exactly. + /// + /// The created content. + private static StringContent CreateJsonContent() + { + StringContent content = new("{}", Encoding.UTF8, "application/json"); + content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + return content; + } +} \ No newline at end of file diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs new file mode 100644 index 00000000..1a26764f --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler.StopScheduledJob; + +/// +/// Contains security tests for the /{culture}/admin/api-scheduled-jobs/{scheduledJobId}/stop route served by the class. +/// +[ExcludeFromCodeCoverage] +public class StopScheduledJobEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public StopScheduledJobEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task StopScheduledJob_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + string url = $"/en-us/admin/api-scheduled-jobs/{Guid.NewGuid()}/stop"; + HttpRequestMessage request = new(HttpMethod.Put, url) + { + Content = CreateJsonContent() + }; + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint.StartsWith("scheduled-jobs", StringComparison.Ordinal)); + } + + [Fact] + public async Task StopScheduledJob_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + string url = $"/en-us/admin/api-scheduled-jobs/{Guid.NewGuid()}/stop"; + HttpRequestMessage request = new(HttpMethod.Put, url) + { + Content = CreateJsonContent() + }; + request.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint.StartsWith("scheduled-jobs", StringComparison.Ordinal)); + } + + /// + /// Creates the empty JSON body of the request; the content type is set without the charset suffix, because the antiforgery middleware matches the content type exactly. + /// + /// The created content. + private static StringContent CreateJsonContent() + { + StringContent content = new("{}", Encoding.UTF8, "application/json"); + content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + return content; + } +} \ No newline at end of file diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs new file mode 100644 index 00000000..b8b8dfaa --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler.UpdateSchedulerDisplayPreferences; + +/// +/// Contains security tests for the /{culture}/admin/api-scheduled-jobs/display-preferences route served by the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateSchedulerDisplayPreferencesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public UpdateSchedulerDisplayPreferencesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task UpdateSchedulerDisplayPreferences_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + string url = "/en-us/admin/api-scheduled-jobs/display-preferences"; + HttpRequestMessage request = new(HttpMethod.Put, url) + { + Content = CreateJsonContent() + }; + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint.StartsWith("scheduled-jobs", StringComparison.Ordinal)); + } + + [Fact] + public async Task UpdateSchedulerDisplayPreferences_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + string url = "/en-us/admin/api-scheduled-jobs/display-preferences"; + HttpRequestMessage request = new(HttpMethod.Put, url) + { + Content = CreateJsonContent() + }; + request.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint.StartsWith("scheduled-jobs", StringComparison.Ordinal)); + } + + /// + /// Creates the empty JSON body of the request; the content type is set without the charset suffix, because the antiforgery middleware matches the content type exactly. + /// + /// The created content. + private static StringContent CreateJsonContent() + { + StringContent content = new("{}", Encoding.UTF8, "application/json"); + content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + return content; + } +} \ No newline at end of file diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/AddScheduledJobRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/AddScheduledJobRequestMappingTests.cs new file mode 100644 index 00000000..4180f78b --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/AddScheduledJobRequestMappingTests.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Application.Core.Scheduling.Commands.AddScheduledJob; +using Lumina.Contracts.Fixtures.Core.Requests.Scheduling; +using Lumina.Contracts.Requests.Scheduling; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddScheduledJobRequestMappingTests +{ + private readonly AddScheduledJobRequestFixture _requestFixture = new(); + + [Fact] + public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + AddScheduledJobRequest request = _requestFixture.Create( + name: "Scan at 6am", + taskType: ScheduledTaskType.ScanMediaLibraries, + scheduleType: ScheduleType.DailyAtHourAndMinute, + hour: 6, + minute: 0); + + // Act + AddScheduledJobCommand result = request.ToCommand(); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.Name, result.Name); + Assert.Equal(request.TaskType, result.TaskType); + Assert.Equal(request.ScheduleType, result.ScheduleType); + Assert.Equal(request.IntervalMinutes, result.IntervalMinutes); + Assert.Equal(request.Hour, result.Hour); + Assert.Equal(request.Minute, result.Minute); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/FireScheduledJobRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/FireScheduledJobRequestMappingTests.cs new file mode 100644 index 00000000..d8cda581 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/FireScheduledJobRequestMappingTests.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Application.Core.Scheduling.Commands.FireScheduledJob; +using Lumina.Contracts.Fixtures.Core.Requests.Scheduling; +using Lumina.Contracts.Requests.Scheduling; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class FireScheduledJobRequestMappingTests +{ + private readonly FireScheduledJobRequestFixture _requestFixture = new(); + + [Fact] + public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + Guid scheduledJobId = Guid.NewGuid(); + FireScheduledJobRequest request = _requestFixture.Create(scheduledJobId); + + // Act + FireScheduledJobCommand result = request.ToCommand(); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.ScheduledJobId, result.ScheduledJobId); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/GetScheduledJobHistoryRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/GetScheduledJobHistoryRequestMappingTests.cs new file mode 100644 index 00000000..f6be56d1 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/GetScheduledJobHistoryRequestMappingTests.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Application.Core.Scheduling.Queries.GetScheduledJobHistory; +using Lumina.Contracts.Fixtures.Core.Requests.Scheduling; +using Lumina.Contracts.Requests.Scheduling; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetScheduledJobHistoryRequestMappingTests +{ + private readonly GetScheduledJobHistoryRequestFixture _requestFixture = new(); + + [Fact] + public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + DateTime from = new(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc); + DateTime to = new(2026, 1, 2, 0, 0, 0, DateTimeKind.Utc); + GetScheduledJobHistoryRequest request = _requestFixture.Create(from, to); + + // Act + GetScheduledJobHistoryQuery result = request.ToQuery(); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.From, result.From); + Assert.Equal(request.To, result.To); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/RemoveScheduledJobRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/RemoveScheduledJobRequestMappingTests.cs new file mode 100644 index 00000000..1afa775e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/RemoveScheduledJobRequestMappingTests.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob; +using Lumina.Contracts.Fixtures.Core.Requests.Scheduling; +using Lumina.Contracts.Requests.Scheduling; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RemoveScheduledJobRequestMappingTests +{ + private readonly RemoveScheduledJobRequestFixture _requestFixture = new(); + + [Fact] + public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + Guid scheduledJobId = Guid.NewGuid(); + RemoveScheduledJobRequest request = _requestFixture.Create(scheduledJobId); + + // Act + RemoveScheduledJobCommand result = request.ToCommand(); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.ScheduledJobId, result.ScheduledJobId); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/ScheduledJobEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/ScheduledJobEntityMappingTests.cs new file mode 100644 index 00000000..dcd6f372 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/ScheduledJobEntityMappingTests.cs @@ -0,0 +1,184 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobEntityMappingTests +{ + private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new(); + + [Fact] + public void ToDomainEntity_WhenRepositoryEntityHasIntervalSchedule_ShouldMapToIntervalScheduledJob() + { + // Arrange + ScheduledJobEntity repositoryEntity = _scheduledJobEntityFixture.Create( + scheduleType: ScheduleType.WithIntervalInMinutes, + status: ScheduledJobStatus.Active); + + // Act + Result result = repositoryEntity.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(repositoryEntity.Id, result.Value.Id.Value); + Assert.Equal(repositoryEntity.Name, result.Value.Name); + Assert.Equal(repositoryEntity.TaskType, result.Value.TaskType); + Assert.Equal(repositoryEntity.Status, result.Value.Status); + Assert.Equal(repositoryEntity.OwnerUserId, result.Value.OwnerUserId.Value); + IntervalSchedule intervalSchedule = Assert.IsType(result.Value.Schedule); + Assert.Equal(repositoryEntity.IntervalMinutes, intervalSchedule.IntervalMinutes); + if (repositoryEntity.LastStartedOnUtc is not null) + Assert.Equal(repositoryEntity.LastStartedOnUtc.Value, result.Value.LastStartedOnUtc.Value); + if (repositoryEntity.LastCompletedOnUtc is not null) + Assert.Equal(repositoryEntity.LastCompletedOnUtc.Value, result.Value.LastCompletedOnUtc.Value); + } + + [Fact] + public void ToDomainEntity_WhenRepositoryEntityHasDailySchedule_ShouldMapToDailyScheduledJob() + { + // Arrange + ScheduledJobEntity repositoryEntity = _scheduledJobEntityFixture.Create( + scheduleType: ScheduleType.DailyAtHourAndMinute, + hour: 7, + minute: 15); + + // Act + Result result = repositoryEntity.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + DailySchedule dailySchedule = Assert.IsType(result.Value.Schedule); + Assert.Equal(7, dailySchedule.Hour); + Assert.Equal(15, dailySchedule.Minute); + } + + [Fact] + public void ToDomainEntity_WhenIntervalScheduleHasNonPositiveInterval_ShouldReturnError() + { + // Arrange + ScheduledJobEntity repositoryEntity = _scheduledJobEntityFixture.Create( + scheduleType: ScheduleType.WithIntervalInMinutes, + intervalMinutes: 0); + + // Act + Result result = repositoryEntity.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Lumina.Domain.Common.Errors.Errors.Scheduling.IntervalMinutesMustBePositive, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenDailyScheduleHasOutOfRangeHour_ShouldReturnError() + { + // Arrange + ScheduledJobEntity repositoryEntity = _scheduledJobEntityFixture.Create( + scheduleType: ScheduleType.DailyAtHourAndMinute, + hour: 30, + minute: 0); + + // Act + Result result = repositoryEntity.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + } + + [Fact] + public void ToDomainEntities_WhenCalledWithCollection_ShouldMapEveryRepositoryEntity() + { + // Arrange + List repositoryEntities = + [ + _scheduledJobEntityFixture.Create(scheduleType: ScheduleType.WithIntervalInMinutes), + _scheduledJobEntityFixture.Create(scheduleType: ScheduleType.DailyAtHourAndMinute) + ]; + + // Act + List> results = repositoryEntities.ToDomainEntities().ToList(); + + // Assert + Assert.Equal(2, results.Count); + Assert.All(results, result => Assert.False(result.IsFailure)); + } + + [Fact] + public void ToResponse_WhenRepositoryEntityHasIntervalSchedule_ShouldMapToResponse() + { + // Arrange + ScheduledJobEntity repositoryEntity = _scheduledJobEntityFixture.Create( + id: Guid.NewGuid(), + scheduleType: ScheduleType.WithIntervalInMinutes, + intervalMinutes: 45, + status: ScheduledJobStatus.Active); + + // Act + ScheduledJobResponse result = repositoryEntity.ToResponse(); + + // Assert + Assert.NotNull(result); + Assert.Equal(repositoryEntity.Id, result.Id); + Assert.Equal(repositoryEntity.Name, result.Name); + Assert.Equal(repositoryEntity.TaskType, result.TaskType); + Assert.Equal(ScheduleType.WithIntervalInMinutes, result.ScheduleType); + Assert.Equal(45, result.IntervalMinutes); + Assert.Null(result.Hour); + Assert.Null(result.Minute); + Assert.Equal(ScheduledJobStatus.Active, result.Status); + Assert.Equal(repositoryEntity.LastStartedOnUtc, result.LastStartedOnUtc); + Assert.Equal(repositoryEntity.LastCompletedOnUtc, result.LastCompletedOnUtc); + } + + [Fact] + public void ToDomainEntity_WhenRepositoryEntityHasOnceAtStartupSchedule_ShouldMapToOnceAtStartupScheduledJob() + { + // Arrange + ScheduledJobEntity repositoryEntity = _scheduledJobEntityFixture.Create( + scheduleType: ScheduleType.OnceAtStartup, + status: ScheduledJobStatus.Active); + + // Act + Result result = repositoryEntity.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + OnceAtStartupSchedule onceAtStartupSchedule = Assert.IsType(result.Value.Schedule); + Assert.Equal(ScheduleType.OnceAtStartup, onceAtStartupSchedule.ScheduleType); + } + + [Fact] + public void ToResponse_WhenRepositoryEntityHasOnceAtStartupSchedule_ShouldMapToResponse() + { + // Arrange + ScheduledJobEntity repositoryEntity = _scheduledJobEntityFixture.Create( + id: Guid.NewGuid(), + scheduleType: ScheduleType.OnceAtStartup, + status: ScheduledJobStatus.Active); + + // Act + ScheduledJobResponse result = repositoryEntity.ToResponse(); + + // Assert + Assert.NotNull(result); + Assert.Equal(ScheduleType.OnceAtStartup, result.ScheduleType); + Assert.Null(result.IntervalMinutes); + Assert.Null(result.Hour); + Assert.Null(result.Minute); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/ScheduledJobExecutionEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/ScheduledJobExecutionEntityMappingTests.cs new file mode 100644 index 00000000..a165bce5 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/ScheduledJobExecutionEntityMappingTests.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobExecutionEntityMappingTests +{ + private readonly ScheduledJobExecutionEntityFixture _scheduledJobExecutionEntityFixture = new(); + + [Fact] + public void ToResponse_WhenRepositoryEntityIsCompleted_ShouldMapToResponse() + { + // Arrange + DateTime startedOnUtc = DateTime.UtcNow.AddMinutes(-10); + DateTime completedOnUtc = DateTime.UtcNow; + ScheduledJobExecutionEntity repositoryEntity = _scheduledJobExecutionEntityFixture.Create( + scheduledJobId: Guid.NewGuid(), + isCycleRun: true, + startedOnUtc: startedOnUtc, + completedOnUtc: completedOnUtc); + + // Act + ScheduledJobExecutionResponse result = repositoryEntity.ToResponse(); + + // Assert + Assert.NotNull(result); + Assert.Equal(repositoryEntity.Id, result.Id); + Assert.Equal(repositoryEntity.ScheduledJobId, result.ScheduledJobId); + Assert.Equal(repositoryEntity.TaskType, result.TaskType); + Assert.True(result.IsCycleRun); + Assert.Equal(startedOnUtc, result.StartedOnUtc); + Assert.Equal(completedOnUtc, result.CompletedOnUtc); + } + + [Fact] + public void ToResponse_WhenRepositoryEntityIsStillRunning_ShouldMapToResponseWithNullCompletionTime() + { + // Arrange + ScheduledJobExecutionEntity repositoryEntity = _scheduledJobExecutionEntityFixture.Create( + isCycleRun: false, + completedOnUtc: null); + + // Act + ScheduledJobExecutionResponse result = repositoryEntity.ToResponse(); + + // Assert + Assert.NotNull(result); + Assert.Equal(repositoryEntity.Id, result.Id); + Assert.False(result.IsCycleRun); + Assert.Null(result.CompletedOnUtc); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/ScheduledJobMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/ScheduledJobMappingTests.cs new file mode 100644 index 00000000..67abb195 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/ScheduledJobMappingTests.cs @@ -0,0 +1,117 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobMappingTests +{ + private readonly ScheduledJobFixture _scheduledJobFixture = new(); + + [Fact] + public void ToRepositoryEntity_WhenDomainEntityHasIntervalSchedule_ShouldMapToRepositoryEntity() + { + // Arrange + Guid ownerUserId = Guid.NewGuid(); + Result intervalScheduleResult = IntervalSchedule.Create(30); + ScheduledJob domainEntity = _scheduledJobFixture.Create( + name: "Interval job", + taskType: ScheduledTaskType.ScanMediaLibraries, + schedule: intervalScheduleResult.Value, + ownerUserId: ownerUserId); + + // Act + ScheduledJobEntity result = domainEntity.ToRepositoryEntity(); + + // Assert + Assert.NotNull(result); + Assert.Equal(domainEntity.Id.Value, result.Id); + Assert.Equal(domainEntity.Name, result.Name); + Assert.Equal(domainEntity.TaskType, result.TaskType); + Assert.Equal(ScheduleType.WithIntervalInMinutes, result.ScheduleType); + Assert.Equal(30, result.IntervalMinutes); + Assert.Null(result.Hour); + Assert.Null(result.Minute); + Assert.Equal(domainEntity.Status, result.Status); + Assert.Equal(ownerUserId, result.OwnerUserId); + Assert.False(result.LastStartedOnUtc.HasValue); + Assert.False(result.LastCompletedOnUtc.HasValue); + } + + [Fact] + public void ToRepositoryEntity_WhenDomainEntityHasDailySchedule_ShouldMapToRepositoryEntity() + { + // Arrange + Result dailyScheduleResult = DailySchedule.Create(9, 45); + ScheduledJob domainEntity = _scheduledJobFixture.Create( + name: "Daily job", + taskType: ScheduledTaskType.CleanTemporaryFiles, + schedule: dailyScheduleResult.Value); + + // Act + ScheduledJobEntity result = domainEntity.ToRepositoryEntity(); + + // Assert + Assert.NotNull(result); + Assert.Equal(ScheduleType.DailyAtHourAndMinute, result.ScheduleType); + Assert.Null(result.IntervalMinutes); + Assert.Equal(9, result.Hour); + Assert.Equal(45, result.Minute); + } + + [Fact] + public void ToResponse_WhenDomainEntityHasIntervalSchedule_ShouldMapToResponse() + { + // Arrange + Result intervalScheduleResult = IntervalSchedule.Create(120); + ScheduledJob domainEntity = _scheduledJobFixture.Create( + name: "Interval job", + schedule: intervalScheduleResult.Value); + + // Act + ScheduledJobResponse result = domainEntity.ToResponse(); + + // Assert + Assert.NotNull(result); + Assert.Equal(domainEntity.Id.Value, result.Id); + Assert.Equal(domainEntity.Name, result.Name); + Assert.Equal(ScheduleType.WithIntervalInMinutes, result.ScheduleType); + Assert.Equal(120, result.IntervalMinutes); + Assert.Null(result.Hour); + Assert.Null(result.Minute); + Assert.Equal(domainEntity.Status, result.Status); + } + + [Fact] + public void ToResponse_WhenDomainEntityHasDailySchedule_ShouldMapToResponse() + { + // Arrange + Result dailyScheduleResult = DailySchedule.Create(5, 0); + ScheduledJob domainEntity = _scheduledJobFixture.Create( + name: "Daily job", + schedule: dailyScheduleResult.Value); + + // Act + ScheduledJobResponse result = domainEntity.ToResponse(); + + // Assert + Assert.NotNull(result); + Assert.Equal(ScheduleType.DailyAtHourAndMinute, result.ScheduleType); + Assert.Null(result.IntervalMinutes); + Assert.Equal(5, result.Hour); + Assert.Equal(0, result.Minute); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/SchedulerDisplayPreferencesEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/SchedulerDisplayPreferencesEntityMappingTests.cs new file mode 100644 index 00000000..4bdd2563 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/SchedulerDisplayPreferencesEntityMappingTests.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SchedulerDisplayPreferencesEntityMappingTests +{ + private readonly SchedulerDisplayPreferencesEntityFixture _schedulerDisplayPreferencesEntityFixture = new(); + + [Fact] + public void ToResponse_WhenRepositoryEntityExists_ShouldMapToResponse() + { + // Arrange + Guid userId = Guid.NewGuid(); + SchedulerDisplayPreferencesEntity repositoryEntity = _schedulerDisplayPreferencesEntityFixture.Create( + userId: userId, + jobTypeFilter: ScheduledTaskType.CleanTemporaryFiles, + displayTimeSpan: 30, + displayTimeUnit: SchedulerDisplayTimeUnit.Minutes); + + // Act + SchedulerDisplayPreferencesResponse result = repositoryEntity.ToResponse(); + + // Assert + Assert.NotNull(result); + Assert.Equal(userId, result.UserId); + Assert.Equal(ScheduledTaskType.CleanTemporaryFiles, result.JobTypeFilter); + Assert.Equal(30, result.DisplayTimeSpan); + Assert.Equal(SchedulerDisplayTimeUnit.Minutes, result.DisplayTimeUnit); + } + + [Fact] + public void ToDefaultResponse_WhenRepositoryEntityIsNull_ShouldReturnDefaultResponseForTheUser() + { + // Arrange + Guid userId = Guid.NewGuid(); + + // Act + SchedulerDisplayPreferencesResponse result = ((SchedulerDisplayPreferencesEntity?)null).ToDefaultResponse(userId); + + // Assert + Assert.NotNull(result); + Assert.Equal(userId, result.UserId); + Assert.Null(result.JobTypeFilter); + Assert.Equal(10, result.DisplayTimeSpan); + Assert.Equal(SchedulerDisplayTimeUnit.Minutes, result.DisplayTimeUnit); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/StartScheduledJobRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/StartScheduledJobRequestMappingTests.cs new file mode 100644 index 00000000..374c6a6b --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/StartScheduledJobRequestMappingTests.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Application.Core.Scheduling.Commands.StartScheduledJob; +using Lumina.Contracts.Fixtures.Core.Requests.Scheduling; +using Lumina.Contracts.Requests.Scheduling; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class StartScheduledJobRequestMappingTests +{ + private readonly StartScheduledJobRequestFixture _requestFixture = new(); + + [Fact] + public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + Guid scheduledJobId = Guid.NewGuid(); + StartScheduledJobRequest request = _requestFixture.Create(scheduledJobId); + + // Act + StartScheduledJobCommand result = request.ToCommand(); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.ScheduledJobId, result.ScheduledJobId); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/StopScheduledJobRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/StopScheduledJobRequestMappingTests.cs new file mode 100644 index 00000000..d67d254f --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/StopScheduledJobRequestMappingTests.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Application.Core.Scheduling.Commands.StopScheduledJob; +using Lumina.Contracts.Fixtures.Core.Requests.Scheduling; +using Lumina.Contracts.Requests.Scheduling; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class StopScheduledJobRequestMappingTests +{ + private readonly StopScheduledJobRequestFixture _requestFixture = new(); + + [Fact] + public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + Guid scheduledJobId = Guid.NewGuid(); + StopScheduledJobRequest request = _requestFixture.Create(scheduledJobId); + + // Act + StopScheduledJobCommand result = request.ToCommand(); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.ScheduledJobId, result.ScheduledJobId); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/UpdateSchedulerDisplayPreferencesRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/UpdateSchedulerDisplayPreferencesRequestMappingTests.cs new file mode 100644 index 00000000..3b09a096 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/UpdateSchedulerDisplayPreferencesRequestMappingTests.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Application.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences; +using Lumina.Contracts.Fixtures.Core.Requests.Scheduling; +using Lumina.Contracts.Requests.Scheduling; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateSchedulerDisplayPreferencesRequestMappingTests +{ + private readonly UpdateSchedulerDisplayPreferencesRequestFixture _requestFixture = new(); + + [Fact] + public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + UpdateSchedulerDisplayPreferencesRequest request = _requestFixture.Create( + jobTypeFilter: ScheduledTaskType.CleanTemporaryFiles, + displayTimeSpan: 15, + displayTimeUnit: SchedulerDisplayTimeUnit.Hours); + + // Act + UpdateSchedulerDisplayPreferencesCommand result = request.ToCommand(); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.JobTypeFilter, result.JobTypeFilter); + Assert.Equal(request.DisplayTimeSpan, result.DisplayTimeSpan); + Assert.Equal(request.DisplayTimeUnit, result.DisplayTimeUnit); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs index ef38a48c..685422b6 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs @@ -1,18 +1,24 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.Seed; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DomainEvents; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Fixtures.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; using Lumina.Contracts.Responses.Authentication; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; using NSubstitute; using System; using System.Diagnostics.CodeAnalysis; @@ -35,10 +41,14 @@ public class SetupApplicationCommandHandlerTests private readonly ITotpTokenGenerator _mockTotpTokenGenerator; private readonly IQRCodeGenerator _mockQRCodeGenerator; private readonly IUserRepository _mockUserRepository; + private readonly IScheduledJobRepository _mockScheduledJobRepository; private readonly IDateTimeProvider _mockDateTimeProvider; private readonly IDataSeedService _mockDataSeedService; + private readonly IDomainEventsQueue _mockDomainEventsQueue; + private readonly IValidator _mockValidator; private readonly SetupApplicationCommandHandler _sut; private readonly UserEntityFixture _userEntityFixture = new(); + private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new(); private readonly SetupApplicationCommandFixture _setupApplicationCommandFixture = new(); /// @@ -52,14 +62,21 @@ public class SetupApplicationCommandHandlerTests _mockTotpTokenGenerator = Substitute.For(); _mockQRCodeGenerator = Substitute.For(); _mockUserRepository = Substitute.For(); + _mockScheduledJobRepository = Substitute.For(); _mockDateTimeProvider = Substitute.For(); _mockDataSeedService = Substitute.For(); - IValidator mockValidator = Substitute.For>(); - mockValidator.Validate(Arg.Any()) + _mockDomainEventsQueue = Substitute.For(); + _mockValidator = Substitute.For>(); + _mockValidator.Validate(Arg.Any()) .Returns([]); _mockUnitOfWork.UserRepository.Returns(_mockUserRepository); + _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); _mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow); + _mockDataSeedService.SetDefaultScheduledJobsAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockScheduledJobRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From(Enumerable.Empty())); _sut = new SetupApplicationCommandHandler( _mockUnitOfWork, @@ -69,7 +86,8 @@ public class SetupApplicationCommandHandlerTests _mockQRCodeGenerator, _mockDateTimeProvider, _mockDataSeedService, - mockValidator); + _mockDomainEventsQueue, + _mockValidator); } [Fact] @@ -336,6 +354,40 @@ public class SetupApplicationCommandHandlerTests await _mockDataSeedService.Received(1).SetDefaultAuthorizationRolesAsync(Arg.Any(), Arg.Any()); await _mockDataSeedService.Received(1).SetAdminRolePermissionsAsync(Arg.Any(), Arg.Any()); await _mockDataSeedService.Received(1).SetAdminRoleToAdministratorAccount(Arg.Any(), Arg.Any()); + await _mockDataSeedService.DidNotReceive().SetDefaultScheduledJobsAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSeedingDefaultScheduledJobsFails_ShouldReturnError() + { + // Arrange + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to seed default scheduled jobs"); + + _mockUserRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetDefaultScheduledJobsAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + + await _mockDataSeedService.Received(1).SetAdminRoleToAdministratorAccount(Arg.Any(), Arg.Any()); + await _mockDataSeedService.Received(1).SetDefaultScheduledJobsAsync(Arg.Any(), Arg.Any()); } [Fact] @@ -369,5 +421,90 @@ public class SetupApplicationCommandHandlerTests await _mockDataSeedService.Received(1).SetDefaultAuthorizationRolesAsync(Arg.Any(), Arg.Any()); await _mockDataSeedService.Received(1).SetAdminRolePermissionsAsync(Arg.Any(), Arg.Any()); await _mockDataSeedService.Received(1).SetAdminRoleToAdministratorAccount(Arg.Any(), Arg.Any()); + await _mockDataSeedService.Received(1).SetDefaultScheduledJobsAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenDefaultScheduledJobsAreSeeded_ShouldQueueACycleStartedEventForEachActiveJob() + { + // Arrange + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); + ScheduledJobEntity activeScheduledJob1 = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active); + ScheduledJobEntity activeScheduledJob2 = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active); + ScheduledJobEntity addedScheduledJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added); + + _mockUserRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockScheduledJobRepository.GetAllAsync(Arg.Any()) + .Returns(new[] { activeScheduledJob1, activeScheduledJob2, addedScheduledJob }); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockDomainEventsQueue.Received(1).Enqueue(Arg.Is(domainEvent => domainEvent.ScheduledJobId.Value == activeScheduledJob1.Id)); + _mockDomainEventsQueue.Received(1).Enqueue(Arg.Is(domainEvent => domainEvent.ScheduledJobId.Value == activeScheduledJob2.Id)); + _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Is(domainEvent => domainEvent.ScheduledJobId.Value == addedScheduledJob.Id)); + } + + [Fact] + public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotCreateAnyUser() + { + // Arrange + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); + Error validationError = Error.Validation("Setup.Validation", "The setup command is invalid."); + _mockValidator.Validate(Arg.Any()).Returns([validationError]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(validationError, result.FirstError); + await _mockUserRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenReadingTheSeededScheduledJobsFails_ShouldReturnTheRepositoryError() + { + // Arrange + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); + _mockUserRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From(Enumerable.Empty())); + _mockHashService.HashString(command.Password!) + .Returns("hashedPassword"); + _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + Error expectedError = Error.Failure("ScheduledJobs.NotFound", "Failed to read the scheduled jobs"); + _mockScheduledJobRepository.GetAllAsync(Arg.Any()) + .Returns(expectedError); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(expectedError, result.FirstError); + _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandlerTests.cs index 93451f92..293a41b1 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandlerTests.cs @@ -10,6 +10,7 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; using Microsoft.Extensions.Options; using NSubstitute; using System; @@ -31,6 +32,7 @@ public class LibraryDeletedDomainEventHandlerTests private readonly IPathService _mockPathService; private readonly LibraryDeletedDomainEventHandler _sut; private readonly LibraryFixture _libraryFixture = new(); + private readonly LibraryDeletedDomainEventFixture _libraryDeletedDomainEventFixture = new(); private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new(); /// @@ -64,7 +66,7 @@ public class LibraryDeletedDomainEventHandlerTests // Arrange Guid libraryId = Guid.NewGuid(); Library library = _libraryFixture.Create(id: libraryId); - LibraryDeletedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow); + LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library); // Act await _sut.HandleAsync(domainEvent, CancellationToken.None); @@ -80,7 +82,7 @@ public class LibraryDeletedDomainEventHandlerTests // Arrange Guid libraryId = Guid.NewGuid(); Library library = _libraryFixture.Create(id: libraryId); - LibraryDeletedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow); + LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library); Error error = Error.Failure(description: "Failed to delete library directory"); _mockDirectoryProviderService.DeleteDirectory(Arg.Any()).Returns(error); @@ -98,7 +100,7 @@ public class LibraryDeletedDomainEventHandlerTests // Arrange Guid libraryId = Guid.NewGuid(); Library library = _libraryFixture.Create(id: libraryId); - LibraryDeletedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow); + LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library); Error error = Error.Failure(description: "Failed to combine path"); _mockPathService.CombinePath(Arg.Any(), Arg.Any()).Returns(error); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandlerTests.cs index f0d866f7..aec3802f 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandlerTests.cs @@ -12,10 +12,8 @@ using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; -using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; -using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Microsoft.Extensions.Logging; using NSubstitute; using System; @@ -40,10 +38,9 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests private readonly ILogger _mockLogger; private readonly LibraryMediaItemDeletedDomainEventHandler _sut; private readonly LibraryIdFixture _libraryIdFixture = new(); - private readonly ScanIdFixture _scanIdFixture = new(); - private readonly UserIdFixture _userIdFixture = new(); private readonly BookEntityFixture _bookEntityFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryMediaItemDeletedDomainEventFixture _libraryMediaItemDeletedDomainEventFixture = new(); /// /// Initializes a new instance of the class. @@ -81,12 +78,7 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests .Returns(Result.Deleted); _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); - LibraryMediaItemDeletedDomainEvent domainEvent = new( - Guid.NewGuid(), - libraryId, - MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()), - book.Path, - DateTime.UtcNow); + LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: book.Path); // Act await _sut.HandleAsync(domainEvent, CancellationToken.None); @@ -105,12 +97,7 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests _mockBookRepository.GetByPathAsync(libraryId.Value, "/books/deleted.epub", Arg.Any()) .Returns(Result.From(null)); - LibraryMediaItemDeletedDomainEvent domainEvent = new( - Guid.NewGuid(), - libraryId, - MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()), - "/books/deleted.epub", - DateTime.UtcNow); + LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: "/books/deleted.epub"); // Act await _sut.HandleAsync(domainEvent, CancellationToken.None); @@ -140,12 +127,7 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests .Returns(Result.From(Result.Deleted)); _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); - LibraryMediaItemDeletedDomainEvent domainEvent = new( - Guid.NewGuid(), - libraryId, - MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()), - book.Path, - DateTime.UtcNow); + LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: book.Path); // Act await _sut.HandleAsync(domainEvent, CancellationToken.None); @@ -165,12 +147,7 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests _mockBookRepository.GetByPathAsync(libraryId.Value, "/books/deleted.epub", Arg.Any()) .Returns(error); - LibraryMediaItemDeletedDomainEvent domainEvent = new( - Guid.NewGuid(), - libraryId, - MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()), - "/books/deleted.epub", - DateTime.UtcNow); + LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: "/books/deleted.epub"); // Act EventualConsistencyException exception = await Assert.ThrowsAsync( @@ -200,12 +177,7 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests _mockBookRepository.DeleteAsync(book.Id, Arg.Any()) .Returns(error); - LibraryMediaItemDeletedDomainEvent domainEvent = new( - Guid.NewGuid(), - libraryId, - MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()), - book.Path, - DateTime.UtcNow); + LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: book.Path); // Act EventualConsistencyException exception = await Assert.ThrowsAsync( diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandlerTests.cs index 267c59ec..b156d8c5 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandlerTests.cs @@ -15,6 +15,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; using Microsoft.Extensions.Options; using NSubstitute; @@ -43,6 +44,7 @@ public class LibrarySavedDomainEventHandlerTests private readonly IPathService _mockPathService; private readonly LibrarySavedDomainEventHandler _sut; private readonly LibraryFixture _libraryFixture = new(); + private readonly LibrarySavedDomainEventFixture _librarySavedDomainEventFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new(); private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new(); @@ -97,14 +99,14 @@ public class LibrarySavedDomainEventHandlerTests // Arrange Guid libraryId = Guid.NewGuid(); Library library = _libraryFixture.Create(id: libraryId, coverImage: "C:/Users/user/cover.jpg"); - LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow); + LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(library: library); LibraryEntity updatedLibrary = _libraryEntityFixture.Create(id: libraryId); // Act await _sut.HandleAsync(domainEvent, CancellationToken.None); // Assert - Assert.NotNull(library.CoverImage); + Assert.NotNull(domainEvent.Library.CoverImage); await _mockLibraryRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } @@ -115,7 +117,7 @@ public class LibrarySavedDomainEventHandlerTests // Arrange Guid libraryId = Guid.NewGuid(); Library library = _libraryFixture.Create(id: libraryId, coverImage: "C:/Users/user/cover.jpg"); - LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow); + LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(library: library); _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(Result.From(true)); _mockFileProviderService.GetFilePaths(Arg.Any(), true) .Returns(Result.From>( @@ -140,7 +142,7 @@ public class LibrarySavedDomainEventHandlerTests // Arrange Guid libraryId = Guid.NewGuid(); Library library = _libraryFixture.Create(id: libraryId, includeCoverImage: false); - LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow); + LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(library: library); _mockFileProviderService.GetFilePaths(Arg.Any(), true) .Returns(Result.From>( [ @@ -162,7 +164,7 @@ public class LibrarySavedDomainEventHandlerTests // Arrange Guid libraryId = Guid.NewGuid(); Library library = _libraryFixture.Create(id: libraryId, coverImage: "/Media/Libraries/guid/cover.png"); - LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow); + LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(library: library); // mirror the real CombinePath behavior, which treats the combined name as a directory segment and appends a trailing // separator; the internal cover path resolution must still yield the file path without that trailing separator _mockPathService.CombinePath(Arg.Any(), Arg.Any()) @@ -175,7 +177,7 @@ public class LibrarySavedDomainEventHandlerTests await _sut.HandleAsync(domainEvent, CancellationToken.None); // Assert - Assert.Equal("/Media/Libraries/guid/cover.png", library.CoverImage); + Assert.Equal("/Media/Libraries/guid/cover.png", domainEvent.Library.CoverImage); _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), Arg.Any()); await _mockLibraryRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); } @@ -186,7 +188,7 @@ public class LibrarySavedDomainEventHandlerTests // Arrange Guid libraryId = Guid.NewGuid(); Library library = _libraryFixture.Create(id: libraryId, coverImage: "C:/Users/user/cover.jpg"); - LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow); + LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(library: library); _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(false)); // Act @@ -204,7 +206,7 @@ public class LibrarySavedDomainEventHandlerTests // Arrange Guid libraryId = Guid.NewGuid(); Library library = _libraryFixture.Create(id: libraryId, coverImage: "C:/Users/user/cover.jpg"); - LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow); + LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(library: library); _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(ImageType.None)); @@ -223,7 +225,7 @@ public class LibrarySavedDomainEventHandlerTests // Arrange Guid libraryId = Guid.NewGuid(); Library library = _libraryFixture.Create(id: libraryId, coverImage: "C:/Users/user/cover.jpg"); - LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow); + LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(library: library); Error error = Error.Failure(description: "Failed to copy cover file"); _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) .Returns(error); @@ -243,7 +245,7 @@ public class LibrarySavedDomainEventHandlerTests // Arrange Guid libraryId = Guid.NewGuid(); Library library = _libraryFixture.Create(id: libraryId, includeCoverImage: false); - LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow); + LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(library: library); Error error = Error.Failure(description: "Failed to combine path"); _mockPathService.CombinePath(Arg.Any(), Arg.Any()).Returns(error); @@ -262,7 +264,7 @@ public class LibrarySavedDomainEventHandlerTests // Arrange Guid libraryId = Guid.NewGuid(); Library library = _libraryFixture.Create(id: libraryId, coverImage: "C:/Users/user/cover.jpg"); - LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow); + LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(library: library); Error error = Error.Failure(description: "Failed to update library"); _mockLibraryRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(error); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandlerTests.cs index 8833f45b..0930c15e 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandlerTests.cs @@ -12,8 +12,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; -using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; -using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using DomainErrors = Lumina.Domain.Common.Errors.Errors; using NSubstitute; using System; @@ -39,8 +38,7 @@ public class LibraryScanCancelledDomainEventHandlerTests private readonly IMediaLibrariesScanCancellationTracker _mockMediaLibrariesScanCancellationTracker; private readonly LibraryScanCancelledDomainEventHandler _sut; private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new(); - private readonly ScanIdFixture _scanIdFixture = new(); - private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly LibraryScanCancelledDomainEventFixture _libraryScanCancelledDomainEventFixture = new(); /// /// Initializes a new instance of the class. @@ -68,8 +66,10 @@ public class LibraryScanCancelledDomainEventHandlerTests public async Task HandleAsync_WhenScanExists_ShouldCancelScanAndCleanupResources() { // Arrange - LibraryScanEntity scan = _libraryScanEntityFixture.Create(); - LibraryScanCancelledDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(value: scan.Id), _libraryIdFixture.Create(value: scan.LibraryId), DateTime.UtcNow); + LibraryScanCancelledDomainEvent domainEvent = _libraryScanCancelledDomainEventFixture.Create(); + LibraryScanEntity scan = _libraryScanEntityFixture.Create( + id: domainEvent.ScanId.Value, + libraryId: domainEvent.LibraryId.Value); _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) .Returns(Result.From(scan)); @@ -87,7 +87,7 @@ public class LibraryScanCancelledDomainEventHandlerTests public async Task HandleAsync_WhenGetByIdFails_ShouldThrowEventualConsistencyException() { // Arrange - LibraryScanCancelledDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(), _libraryIdFixture.Create(), DateTime.UtcNow); + LibraryScanCancelledDomainEvent domainEvent = _libraryScanCancelledDomainEventFixture.Create(); Error error = Error.Failure(description: "Failed to get library scan"); _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) .Returns(error); @@ -105,7 +105,7 @@ public class LibraryScanCancelledDomainEventHandlerTests public async Task HandleAsync_WhenScanDoesNotExist_ShouldThrowEventualConsistencyExceptionWithNotFoundError() { // Arrange - LibraryScanCancelledDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(), _libraryIdFixture.Create(), DateTime.UtcNow); + LibraryScanCancelledDomainEvent domainEvent = _libraryScanCancelledDomainEventFixture.Create(); _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) .Returns(Result.Success(null)); @@ -122,8 +122,10 @@ public class LibraryScanCancelledDomainEventHandlerTests public async Task HandleAsync_WhenCancelScanFails_ShouldThrowEventualConsistencyException() { // Arrange - LibraryScanEntity scan = _libraryScanEntityFixture.Create(); - LibraryScanCancelledDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(value: scan.Id), _libraryIdFixture.Create(value: scan.LibraryId), DateTime.UtcNow); + LibraryScanCancelledDomainEvent domainEvent = _libraryScanCancelledDomainEventFixture.Create(); + LibraryScanEntity scan = _libraryScanEntityFixture.Create( + id: domainEvent.ScanId.Value, + libraryId: domainEvent.LibraryId.Value); _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) .Returns(Result.From(scan)); Error error = Error.Failure(description: "Failed to cancel scan"); @@ -143,8 +145,10 @@ public class LibraryScanCancelledDomainEventHandlerTests public async Task HandleAsync_WhenClearForScanFails_ShouldThrowEventualConsistencyException() { // Arrange - LibraryScanEntity scan = _libraryScanEntityFixture.Create(); - LibraryScanCancelledDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(value: scan.Id), _libraryIdFixture.Create(value: scan.LibraryId), DateTime.UtcNow); + LibraryScanCancelledDomainEvent domainEvent = _libraryScanCancelledDomainEventFixture.Create(); + LibraryScanEntity scan = _libraryScanEntityFixture.Create( + id: domainEvent.ScanId.Value, + libraryId: domainEvent.LibraryId.Value); _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) .Returns(Result.From(scan)); Error error = Error.Failure(description: "Failed to clear staging results"); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandlerTests.cs index aa5de98a..1d6d4e17 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandlerTests.cs @@ -12,9 +12,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; -using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; -using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; -using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using DomainErrors = Lumina.Domain.Common.Errors.Errors; using NSubstitute; @@ -41,10 +39,7 @@ public class LibraryScanFailedDomainEventHandlerTests private readonly IMediaLibraryScanProgressNotifier _mockDebouncedLibraryScanProgressNotifier; private readonly LibraryScanFailedDomainEventHandler _sut; private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new(); - private readonly ScanIdFixture _scanIdFixture = new(); - private readonly UserIdFixture _userIdFixture = new(); - private readonly LibraryIdFixture _libraryIdFixture = new(); - private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new(); + private readonly LibraryScanFailedDomainEventFixture _libraryScanFailedDomainEventFixture = new(); /// /// Initializes a new instance of the class. @@ -73,11 +68,11 @@ public class LibraryScanFailedDomainEventHandlerTests public async Task HandleAsync_WhenScanIsRunning_ShouldFailScanAndCleanupResources() { // Arrange - LibraryScanEntity scan = _libraryScanEntityFixture.Create(); - MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create( - scanId: _scanIdFixture.Create(value: scan.Id), - userId: _userIdFixture.Create(value: scan.UserId)); - LibraryScanFailedDomainEvent domainEvent = new(Guid.NewGuid(), _libraryIdFixture.Create(value: scan.LibraryId), compositeId, DateTime.UtcNow); + LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create(); + MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId; + LibraryScanEntity scan = _libraryScanEntityFixture.Create( + id: compositeId.ScanId.Value, + userId: compositeId.UserId.Value); _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) .Returns(Result.From(scan)); @@ -97,11 +92,12 @@ public class LibraryScanFailedDomainEventHandlerTests public async Task HandleAsync_WhenScanIsNotRunning_ShouldSkipPersistenceButStillCleanupResources() { // Arrange - LibraryScanEntity scan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Failed); - MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create( - scanId: _scanIdFixture.Create(value: scan.Id), - userId: _userIdFixture.Create(value: scan.UserId)); - LibraryScanFailedDomainEvent domainEvent = new(Guid.NewGuid(), _libraryIdFixture.Create(value: scan.LibraryId), compositeId, DateTime.UtcNow); + LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create(); + MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId; + LibraryScanEntity scan = _libraryScanEntityFixture.Create( + id: compositeId.ScanId.Value, + userId: compositeId.UserId.Value, + status: LibraryScanJobStatus.Failed); _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) .Returns(Result.From(scan)); @@ -121,8 +117,7 @@ public class LibraryScanFailedDomainEventHandlerTests public async Task HandleAsync_WhenGetByIdFails_ShouldThrowEventualConsistencyException() { // Arrange - MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); - LibraryScanFailedDomainEvent domainEvent = new(Guid.NewGuid(), _libraryIdFixture.Create(), compositeId, DateTime.UtcNow); + LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create(); Error error = Error.Failure(description: "Failed to get library scan"); _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) .Returns(error); @@ -140,8 +135,7 @@ public class LibraryScanFailedDomainEventHandlerTests public async Task HandleAsync_WhenScanDoesNotExist_ShouldThrowEventualConsistencyExceptionWithNotFoundError() { // Arrange - MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); - LibraryScanFailedDomainEvent domainEvent = new(Guid.NewGuid(), _libraryIdFixture.Create(), compositeId, DateTime.UtcNow); + LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create(); _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) .Returns(Result.Success(null)); @@ -158,11 +152,11 @@ public class LibraryScanFailedDomainEventHandlerTests public async Task HandleAsync_WhenUpdateFails_ShouldThrowEventualConsistencyException() { // Arrange - LibraryScanEntity scan = _libraryScanEntityFixture.Create(); - MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create( - scanId: _scanIdFixture.Create(value: scan.Id), - userId: _userIdFixture.Create(value: scan.UserId)); - LibraryScanFailedDomainEvent domainEvent = new(Guid.NewGuid(), _libraryIdFixture.Create(value: scan.LibraryId), compositeId, DateTime.UtcNow); + LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create(); + MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId; + LibraryScanEntity scan = _libraryScanEntityFixture.Create( + id: compositeId.ScanId.Value, + userId: compositeId.UserId.Value); _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) .Returns(Result.From(scan)); Error error = Error.Failure(description: "Failed to update library scan"); @@ -182,11 +176,11 @@ public class LibraryScanFailedDomainEventHandlerTests public async Task HandleAsync_WhenClearForScanFails_ShouldThrowEventualConsistencyException() { // Arrange - LibraryScanEntity scan = _libraryScanEntityFixture.Create(); - MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create( - scanId: _scanIdFixture.Create(value: scan.Id), - userId: _userIdFixture.Create(value: scan.UserId)); - LibraryScanFailedDomainEvent domainEvent = new(Guid.NewGuid(), _libraryIdFixture.Create(value: scan.LibraryId), compositeId, DateTime.UtcNow); + LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create(); + MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId; + LibraryScanEntity scan = _libraryScanEntityFixture.Create( + id: compositeId.ScanId.Value, + userId: compositeId.UserId.Value); _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) .Returns(Result.From(scan)); Error error = Error.Failure(description: "Failed to clear staging results"); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandlerTests.cs index c73d7af9..8b7c7292 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandlerTests.cs @@ -8,14 +8,11 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Manage using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; -using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; -using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; -using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using DomainErrors = Lumina.Domain.Common.Errors.Errors; using NSubstitute; @@ -41,10 +38,7 @@ public class LibraryScanFinishedDomainEventHandlerTests private readonly IMediaLibraryScanProgressNotifier _mockDebouncedLibraryScanProgressNotifier; private readonly LibraryScanFinishedDomainEventHandler _sut; private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new(); - private readonly ScanIdFixture _scanIdFixture = new(); - private readonly UserIdFixture _userIdFixture = new(); - private readonly LibraryIdFixture _libraryIdFixture = new(); - private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new(); + private readonly LibraryScanFinishedDomainEventFixture _libraryScanFinishedDomainEventFixture = new(); /// /// Initializes a new instance of the class. @@ -69,11 +63,11 @@ public class LibraryScanFinishedDomainEventHandlerTests public async Task HandleAsync_WhenScanIsRunning_ShouldFinishScanAndNotifyClients() { // Arrange - LibraryScanEntity scan = _libraryScanEntityFixture.Create(); - MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create( - scanId: _scanIdFixture.Create(value: scan.Id), - userId: _userIdFixture.Create(value: scan.UserId)); - LibraryScanFinishedDomainEvent domainEvent = new(Guid.NewGuid(), compositeId, DateTime.UtcNow); + LibraryScanFinishedDomainEvent domainEvent = _libraryScanFinishedDomainEventFixture.Create(); + MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId; + LibraryScanEntity scan = _libraryScanEntityFixture.Create( + id: compositeId.ScanId.Value, + userId: compositeId.UserId.Value); _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) .Returns(Result.From(scan)); _mockMediaLibrariesScanProgressTracker.UpdateScanProgress(Arg.Any(), compositeId).Returns(Result.Updated); @@ -93,8 +87,7 @@ public class LibraryScanFinishedDomainEventHandlerTests public async Task HandleAsync_WhenGetByIdFails_ShouldThrowEventualConsistencyException() { // Arrange - MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); - LibraryScanFinishedDomainEvent domainEvent = new(Guid.NewGuid(), compositeId, DateTime.UtcNow); + LibraryScanFinishedDomainEvent domainEvent = _libraryScanFinishedDomainEventFixture.Create(); Error error = Error.Failure(description: "Failed to get library scan"); _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) .Returns(error); @@ -112,8 +105,7 @@ public class LibraryScanFinishedDomainEventHandlerTests public async Task HandleAsync_WhenScanDoesNotExist_ShouldThrowEventualConsistencyExceptionWithNotFoundError() { // Arrange - MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); - LibraryScanFinishedDomainEvent domainEvent = new(Guid.NewGuid(), compositeId, DateTime.UtcNow); + LibraryScanFinishedDomainEvent domainEvent = _libraryScanFinishedDomainEventFixture.Create(); _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) .Returns(Result.Success(null)); @@ -130,11 +122,12 @@ public class LibraryScanFinishedDomainEventHandlerTests public async Task HandleAsync_WhenScanIsNotRunning_ShouldThrowEventualConsistencyException() { // Arrange - LibraryScanEntity scan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Pending); - MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create( - scanId: _scanIdFixture.Create(value: scan.Id), - userId: _userIdFixture.Create(value: scan.UserId)); - LibraryScanFinishedDomainEvent domainEvent = new(Guid.NewGuid(), compositeId, DateTime.UtcNow); + LibraryScanFinishedDomainEvent domainEvent = _libraryScanFinishedDomainEventFixture.Create(); + MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId; + LibraryScanEntity scan = _libraryScanEntityFixture.Create( + id: compositeId.ScanId.Value, + userId: compositeId.UserId.Value, + status: LibraryScanJobStatus.Pending); _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) .Returns(Result.From(scan)); @@ -152,11 +145,11 @@ public class LibraryScanFinishedDomainEventHandlerTests public async Task HandleAsync_WhenUpdateFails_ShouldThrowEventualConsistencyException() { // Arrange - LibraryScanEntity scan = _libraryScanEntityFixture.Create(); - MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create( - scanId: _scanIdFixture.Create(value: scan.Id), - userId: _userIdFixture.Create(value: scan.UserId)); - LibraryScanFinishedDomainEvent domainEvent = new(Guid.NewGuid(), compositeId, DateTime.UtcNow); + LibraryScanFinishedDomainEvent domainEvent = _libraryScanFinishedDomainEventFixture.Create(); + MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId; + LibraryScanEntity scan = _libraryScanEntityFixture.Create( + id: compositeId.ScanId.Value, + userId: compositeId.UserId.Value); _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) .Returns(Result.From(scan)); Error error = Error.Failure(description: "Failed to update library scan"); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanJobProgressChangedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanJobProgressChangedDomainEventHandlerTests.cs index 2ae13b83..ba8553d3 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanJobProgressChangedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanJobProgressChangedDomainEventHandlerTests.cs @@ -6,7 +6,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; -using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using NSubstitute; using System; @@ -26,9 +26,8 @@ public class LibraryScanJobProgressChangedDomainEventHandlerTests private readonly IMediaLibrariesScanProgressTracker _mockMediaLibrariesScanProgressTracker; private readonly IMediaLibraryScanProgressNotifier _mockDebouncedLibraryScanProgressNotifier; private readonly LibraryScanJobProgressChangedDomainEventHandler _sut; - private readonly LibraryIdFixture _libraryIdFixture = new(); - private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new(); private readonly MediaLibraryScanJobProgressFixture _mediaLibraryScanJobProgressFixture = new(); + private readonly LibraryScanJobProgressChangedDomainEventFixture _libraryScanJobProgressChangedDomainEventFixture = new(); /// /// Initializes a new instance of the class. @@ -45,10 +44,10 @@ public class LibraryScanJobProgressChangedDomainEventHandlerTests public async Task HandleAsync_WhenScanJobProgressChanges_ShouldUpdateTrackerAndNotifySignalRClients() { // Arrange - LibraryId libraryId = _libraryIdFixture.Create(); - MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); MediaLibraryScanJobProgress progress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 5, totalItems: 10, currentOperation: "Hashing"); - LibraryScanJobProgressChangedDomainEvent domainEvent = new(Guid.NewGuid(), libraryId, compositeId, progress, DateTime.UtcNow); + LibraryScanJobProgressChangedDomainEvent domainEvent = _libraryScanJobProgressChangedDomainEventFixture.Create(progress: progress); + LibraryId libraryId = domainEvent.LibraryId; + MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId; _mockMediaLibrariesScanProgressTracker.UpdateScanJobProgress(libraryId, compositeId, progress).Returns(Result.Updated); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanProgressChangedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanProgressChangedDomainEventHandlerTests.cs index a3d0bc71..45ec9aee 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanProgressChangedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanProgressChangedDomainEventHandlerTests.cs @@ -6,8 +6,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; -using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; -using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using NSubstitute; using System; using System.Diagnostics.CodeAnalysis; @@ -26,8 +25,7 @@ public class LibraryScanProgressChangedDomainEventHandlerTests private readonly IMediaLibrariesScanProgressTracker _mockMediaLibrariesScanProgressTracker; private readonly IMediaLibraryScanProgressNotifier _mockDebouncedLibraryScanProgressNotifier; private readonly LibraryScanProgressChangedDomainEventHandler _sut; - private readonly LibraryIdFixture _libraryIdFixture = new(); - private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new(); + private readonly LibraryScanProgressChangedDomainEventFixture _libraryScanProgressChangedDomainEventFixture = new(); /// /// Initializes a new instance of the class. @@ -44,9 +42,9 @@ public class LibraryScanProgressChangedDomainEventHandlerTests public async Task HandleAsync_WhenScanProgressChanges_ShouldUpdateTrackerAndNotifySignalRClients() { // Arrange - LibraryId libraryId = _libraryIdFixture.Create(); - MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); - LibraryScanProgressChangedDomainEvent domainEvent = new(Guid.NewGuid(), libraryId, compositeId, DateTime.UtcNow); + LibraryScanProgressChangedDomainEvent domainEvent = _libraryScanProgressChangedDomainEventFixture.Create(); + LibraryId libraryId = domainEvent.LibraryId; + MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId; _mockMediaLibrariesScanProgressTracker.UpdateScanProgress(libraryId, compositeId).Returns(Result.Updated); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandlerTests.cs index 03ef4f4e..7a868cf1 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandlerTests.cs @@ -11,8 +11,7 @@ using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services; -using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; -using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using NSubstitute; using System; @@ -36,8 +35,7 @@ public class LibraryScanQueuedDomainEventHandlerTests private readonly IDomainEventsQueue _mockDomainEventsQueue; private readonly LibraryScanQueuedDomainEventHandler _sut; private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new(); - private readonly ScanIdFixture _scanIdFixture = new(); - private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly LibraryScanQueuedDomainEventFixture _libraryScanQueuedDomainEventFixture = new(); /// /// Initializes a new instance of the class. @@ -61,8 +59,10 @@ public class LibraryScanQueuedDomainEventHandlerTests public async Task HandleAsync_WhenScanExists_ShouldStartTheScan() { // Arrange - LibraryScanEntity scan = _libraryScanEntityFixture.Create(); - LibraryScanQueuedDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(value: scan.Id), _libraryIdFixture.Create(value: scan.LibraryId), DateTime.UtcNow); + LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create(); + LibraryScanEntity scan = _libraryScanEntityFixture.Create( + id: domainEvent.ScanId.Value, + libraryId: domainEvent.LibraryId.Value); _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) .Returns(Result.From(scan)); @@ -80,7 +80,7 @@ public class LibraryScanQueuedDomainEventHandlerTests public async Task HandleAsync_WhenGetByIdFails_ShouldThrowEventualConsistencyException() { // Arrange - LibraryScanQueuedDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(), _libraryIdFixture.Create(), DateTime.UtcNow); + LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create(); Error error = Error.Failure(description: "Failed to get library scan"); _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) .Returns(error); @@ -98,7 +98,7 @@ public class LibraryScanQueuedDomainEventHandlerTests public async Task HandleAsync_WhenScanDoesNotExist_ShouldThrowEventualConsistencyExceptionWithNotFoundError() { // Arrange - LibraryScanQueuedDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(), _libraryIdFixture.Create(), DateTime.UtcNow); + LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create(); _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) .Returns(Result.Success(null)); @@ -115,8 +115,10 @@ public class LibraryScanQueuedDomainEventHandlerTests public async Task HandleAsync_WhenStartScanFails_ShouldThrowEventualConsistencyException() { // Arrange - LibraryScanEntity scan = _libraryScanEntityFixture.Create(); - LibraryScanQueuedDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(value: scan.Id), _libraryIdFixture.Create(value: scan.LibraryId), DateTime.UtcNow); + LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create(); + LibraryScanEntity scan = _libraryScanEntityFixture.Create( + id: domainEvent.ScanId.Value, + libraryId: domainEvent.LibraryId.Value); _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) .Returns(Result.From(scan)); Error error = Error.Failure(description: "Failed to start scan"); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandlerTests.cs index 35944f59..7fcc2a37 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandlerTests.cs @@ -5,9 +5,8 @@ using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Core.MediaLibrary.Management.Events; using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; -using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using NSubstitute; using System; using System.Collections.Generic; @@ -27,7 +26,7 @@ public class LibraryScanStartedDomainEventHandlerTests private readonly IUnitOfWork _mockUnitOfWork; private readonly ILibraryScanRepository _mockLibraryScanRepository; private readonly LibraryScanStartedDomainEventHandler _sut; - private readonly LibraryScanFixture _libraryScanFixture = new(); + private readonly LibraryScanStartedDomainEventFixture _libraryScanStartedDomainEventFixture = new(); /// /// Initializes a new instance of the class. @@ -47,15 +46,14 @@ public class LibraryScanStartedDomainEventHandlerTests public async Task HandleAsync_WhenScanStarts_ShouldUpdateScanStatusAndSaveChanges() { // Arrange - LibraryScan libraryScan = _libraryScanFixture.Create(); - LibraryScanStartedDomainEvent domainEvent = new(Guid.NewGuid(), libraryScan, DateTime.UtcNow); + LibraryScanStartedDomainEvent domainEvent = _libraryScanStartedDomainEventFixture.Create(); // Act await _sut.HandleAsync(domainEvent, CancellationToken.None); // Assert await _mockLibraryScanRepository.Received(1).UpdateAsync( - Arg.Is(scan => scan.Id == libraryScan.Id.Value), + Arg.Is(scan => scan.Id == domainEvent.LibraryScan.Id.Value), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } @@ -64,8 +62,7 @@ public class LibraryScanStartedDomainEventHandlerTests public async Task HandleAsync_WhenUpdateFails_ShouldThrowEventualConsistencyException() { // Arrange - LibraryScan libraryScan = _libraryScanFixture.Create(); - LibraryScanStartedDomainEvent domainEvent = new(Guid.NewGuid(), libraryScan, DateTime.UtcNow); + LibraryScanStartedDomainEvent domainEvent = _libraryScanStartedDomainEventFixture.Create(); Error error = Error.Failure(description: "Failed to update library scan"); _mockLibraryScanRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(error); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandlerTests.cs new file mode 100644 index 00000000..1ba576bb --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandlerTests.cs @@ -0,0 +1,282 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DomainEvents; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Scheduling.Commands.AddScheduledJob; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Fixtures.Core.Scheduling.Commands.AddScheduledJob; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.AddScheduledJob; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddScheduledJobCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly IDomainEventsQueue _mockDomainEventsQueue; + private readonly IScheduledJobRepository _mockScheduledJobRepository; + private readonly IValidator _mockValidator; + private readonly AddScheduledJobCommandHandler _sut; + private readonly AddScheduledJobCommandFixture _addScheduledJobCommandFixture = new(); + private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new(); + private readonly Guid _userId = Guid.NewGuid(); + + /// + /// Initializes a new instance of the class. + /// + public AddScheduledJobCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockDomainEventsQueue = Substitute.For(); + _mockScheduledJobRepository = Substitute.For(); + + _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(true); + + _mockValidator = Substitute.For>(); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new AddScheduledJobCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenCommandIsValidWithIntervalSchedule_ShouldInsertScheduledJobAndReturnResponse() + { + // Arrange + AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.WithIntervalInMinutes); + _mockScheduledJobRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Created); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(command.Name, result.Value.Name); + Assert.Equal(command.TaskType, result.Value.TaskType); + Assert.Equal(ScheduleType.WithIntervalInMinutes, result.Value.ScheduleType); + Assert.Equal(command.IntervalMinutes, result.Value.IntervalMinutes); + Assert.Equal(ScheduledJobStatus.Added, result.Value.Status); + await _mockScheduledJobRepository.Received(1).InsertAsync( + Arg.Is(scheduledJob => + scheduledJob.Name == command.Name && + scheduledJob.TaskType == command.TaskType && + scheduledJob.ScheduleType == ScheduleType.WithIntervalInMinutes && + scheduledJob.IntervalMinutes == command.IntervalMinutes && + scheduledJob.OwnerUserId == _userId), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + _mockDomainEventsQueue.Received(1).Enqueue(Arg.Is(domainEvent => domainEvent is ScheduledJobAddedDomainEvent)); + } + + [Fact] + public async Task HandleAsync_WhenCommandIsValidWithDailySchedule_ShouldInsertScheduledJobAndReturnResponse() + { + // Arrange + AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.DailyAtHourAndMinute, hour: 6, minute: 30); + _mockScheduledJobRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Created); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(ScheduleType.DailyAtHourAndMinute, result.Value.ScheduleType); + Assert.Equal(6, result.Value.Hour); + Assert.Equal(30, result.Value.Minute); + Assert.Null(result.Value.IntervalMinutes); + await _mockScheduledJobRepository.Received(1).InsertAsync( + Arg.Is(scheduledJob => + scheduledJob.ScheduleType == ScheduleType.DailyAtHourAndMinute && + scheduledJob.Hour == 6 && + scheduledJob.Minute == 30), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotPersist() + { + // Arrange + AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([DomainErrors.Scheduling.ScheduledJobNameCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Scheduling.ScheduledJobNameCannotBeEmpty, result.FirstError); + await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedAndNotPersist() + { + // Arrange + AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorizedAndNotPersist() + { + // Arrange + AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenIntervalScheduleHasNonPositiveInterval_ShouldReturnIntervalError() + { + // Arrange + AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create( + scheduleType: ScheduleType.WithIntervalInMinutes, + intervalMinutes: 0); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Scheduling.IntervalMinutesMustBePositive, result.FirstError); + await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenDailyScheduleHasOutOfRangeHour_ShouldReturnHourError() + { + // Arrange + AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create( + scheduleType: ScheduleType.DailyAtHourAndMinute, + hour: 24, + minute: 0); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Scheduling.HourMustBeBetweenZeroAndTwentyThree, result.FirstError); + await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenScheduleTypeIsUnsupported_ShouldReturnInvalidScheduleTypeError() + { + // Arrange + AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: (ScheduleType)999); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Scheduling.InvalidScheduleType, result.FirstError); + await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenScheduledJobNameIsEmpty_ShouldReturnNameErrorAndNotPersist() + { + // Arrange + AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(name: " "); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Scheduling.ScheduledJobNameCannotBeEmpty, result.FirstError); + await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenInsertFails_ShouldReturnErrorAndNotSaveChanges() + { + // Arrange + AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(); + _mockScheduledJobRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(DomainErrors.Scheduling.ScheduledJobAlreadyExists); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Scheduling.ScheduledJobAlreadyExists, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCommandIsValidWithOnceAtStartupSchedule_ShouldInsertScheduledJobAndReturnResponse() + { + // Arrange + AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.OnceAtStartup); + _mockScheduledJobRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Created); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(command.Name, result.Value.Name); + Assert.Equal(ScheduleType.OnceAtStartup, result.Value.ScheduleType); + Assert.Null(result.Value.IntervalMinutes); + Assert.Null(result.Value.Hour); + Assert.Null(result.Value.Minute); + await _mockScheduledJobRepository.Received(1).InsertAsync( + Arg.Is(scheduledJob => + scheduledJob.Name == command.Name && + scheduledJob.ScheduleType == ScheduleType.OnceAtStartup), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + _mockDomainEventsQueue.Received(1).Enqueue(Arg.Is(domainEvent => domainEvent is ScheduledJobAddedDomainEvent)); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandValidatorTests.cs new file mode 100644 index 00000000..cf088601 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandValidatorTests.cs @@ -0,0 +1,195 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Scheduling.Commands.AddScheduledJob; +using Lumina.Application.Fixtures.Core.Scheduling.Commands.AddScheduledJob; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.AddScheduledJob; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddScheduledJobCommandValidatorTests +{ + private readonly AddScheduledJobCommandValidator _validator = new(); + private readonly AddScheduledJobCommandFixture _addScheduledJobCommandFixture = new(); + + [Theory] + [InlineData(null)] // null name + [InlineData("")] // empty name + [InlineData(" ")] // whitespace name + public void Validate_WhenNameIsNullOrWhitespace_ShouldHaveValidationError(string? name) + { + // Arrange + AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create() with { Name = name! }; + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Scheduling.ScheduledJobNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenNameExceedsMaximumLength_ShouldHaveValidationError() + { + // Arrange + AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(name: new string('a', 81)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Scheduling.ScheduledJobNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTaskTypeIsNotInEnum_ShouldHaveValidationError() + { + // Arrange + AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(taskType: (ScheduledTaskType)999); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Scheduling.InvalidScheduleType); + } + + [Fact] + public void Validate_WhenScheduleTypeIsNotInEnum_ShouldHaveValidationError() + { + // Arrange + AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: (ScheduleType)999); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Scheduling.InvalidScheduleType); + } + + [Fact] + public void Validate_WhenIntervalScheduleHasNullInterval_ShouldHaveValidationError() + { + // Arrange + AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.WithIntervalInMinutes) with { IntervalMinutes = null }; + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Scheduling.IntervalMinutesMustBePositive); + } + + [Theory] + [InlineData(0)] // interval of zero + [InlineData(-1)] // negative interval + public void Validate_WhenIntervalScheduleHasNonPositiveInterval_ShouldHaveValidationError(int intervalMinutes) + { + // Arrange + AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create( + scheduleType: ScheduleType.WithIntervalInMinutes, + intervalMinutes: intervalMinutes); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Scheduling.IntervalMinutesMustBePositive); + } + + [Fact] + public void Validate_WhenDailyScheduleHasNullHour_ShouldHaveValidationError() + { + // Arrange + AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.DailyAtHourAndMinute) with { Hour = null }; + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Scheduling.HourMustBeBetweenZeroAndTwentyThree); + } + + [Fact] + public void Validate_WhenDailyScheduleHasNullMinute_ShouldHaveValidationError() + { + // Arrange + AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.DailyAtHourAndMinute) with { Minute = null }; + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Scheduling.MinuteMustBeBetweenZeroAndFiftyNine); + } + + [Theory] + [InlineData(-1)] // hour below the allowed range + [InlineData(24)] // hour above the allowed range + public void Validate_WhenDailyScheduleHasOutOfRangeHour_ShouldHaveValidationError(int hour) + { + // Arrange + AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create( + scheduleType: ScheduleType.DailyAtHourAndMinute, + hour: hour, + minute: 0); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Scheduling.HourMustBeBetweenZeroAndTwentyThree); + } + + [Theory] + [InlineData(-1)] // minute below the allowed range + [InlineData(60)] // minute above the allowed range + public void Validate_WhenDailyScheduleHasOutOfRangeMinute_ShouldHaveValidationError(int minute) + { + // Arrange + AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create( + scheduleType: ScheduleType.DailyAtHourAndMinute, + hour: 12, + minute: minute); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Scheduling.MinuteMustBeBetweenZeroAndFiftyNine); + } + + [Fact] + public void Validate_WhenCommandIsValidWithIntervalSchedule_ShouldNotHaveAnyValidationError() + { + // Arrange + AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.WithIntervalInMinutes); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } + + [Fact] + public void Validate_WhenCommandIsValidWithDailySchedule_ShouldNotHaveAnyValidationError() + { + // Arrange + AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.DailyAtHourAndMinute); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandHandlerTests.cs new file mode 100644 index 00000000..14effc81 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandHandlerTests.cs @@ -0,0 +1,213 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DomainEvents; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Scheduling.Commands.FireScheduledJob; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Fixtures.Core.Scheduling.Commands.FireScheduledJob; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.FireScheduledJob; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class FireScheduledJobCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly IDomainEventsQueue _mockDomainEventsQueue; + private readonly IScheduledJobRepository _mockScheduledJobRepository; + private readonly IValidator _mockValidator; + private readonly FireScheduledJobCommandHandler _sut; + private readonly FireScheduledJobCommandFixture _fireScheduledJobCommandFixture = new(); + private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new(); + private readonly Guid _userId = Guid.NewGuid(); + + /// + /// Initializes a new instance of the class. + /// + public FireScheduledJobCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockDomainEventsQueue = Substitute.For(); + _mockScheduledJobRepository = Substitute.For(); + + _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(true); + + _mockValidator = Substitute.For>(); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new FireScheduledJobCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenScheduledJobIsAdded_ShouldEnqueueFiredEventAndReturnResponse() + { + // Arrange + FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create(); + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create( + id: command.ScheduledJobId, + scheduleType: ScheduleType.WithIntervalInMinutes, + status: ScheduledJobStatus.Active); + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(Result.From(scheduledJob)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(scheduledJob.Name, result.Value.Name); + _mockDomainEventsQueue.Received(1).Enqueue(Arg.Is(domainEvent => domainEvent is ScheduledJobFiredDomainEvent)); + await _mockScheduledJobRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotQueueEvent() + { + // Arrange + FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([DomainErrors.Scheduling.ScheduledJobNotFound]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized() + { + // Arrange + FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized() + { + // Arrange + FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create(); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetByIdReturnsError_ShouldReturnError() + { + // Arrange + FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to get the scheduled job"); + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()).Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenScheduledJobDoesNotExist_ShouldReturnNotFound() + { + // Arrange + FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create(); + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError); + _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenToDomainEntityFails_ShouldReturnError() + { + // Arrange + FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create(); + // A daily scheduled job with an out of range hour cannot convert to its domain aggregate. + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create( + id: command.ScheduledJobId, + scheduleType: ScheduleType.DailyAtHourAndMinute, + hour: 99, + minute: 0); + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(Result.From(scheduledJob)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenScheduledJobIsRunning_ShouldReturnAlreadyRunningError() + { + // Arrange + FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create(); + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create( + id: command.ScheduledJobId, + scheduleType: ScheduleType.WithIntervalInMinutes, + status: ScheduledJobStatus.Running); + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(Result.From(scheduledJob)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Scheduling.ScheduledJobAlreadyRunning, result.FirstError); + _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandValidatorTests.cs new file mode 100644 index 00000000..6a9c57d7 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandValidatorTests.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Scheduling.Commands.FireScheduledJob; +using Lumina.Application.Fixtures.Core.Scheduling.Commands.FireScheduledJob; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.FireScheduledJob; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class FireScheduledJobCommandValidatorTests +{ + private readonly FireScheduledJobCommandValidator _validator = new(); + private readonly FireScheduledJobCommandFixture _fireScheduledJobCommandFixture = new(); + + [Fact] + public void Validate_WhenScheduledJobIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create() with { ScheduledJobId = Guid.Empty }; + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Scheduling.ScheduledJobNotFound); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError() + { + // Arrange + FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandlerTests.cs new file mode 100644 index 00000000..93a48823 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandlerTests.cs @@ -0,0 +1,262 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DomainEvents; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Scheduling; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Fixtures.Core.Scheduling.Commands.RemoveScheduledJob; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +using ScheduledJobId = Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects.ScheduledJobId; +#endregion + +namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.RemoveScheduledJob; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RemoveScheduledJobCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly IDomainEventsQueue _mockDomainEventsQueue; + private readonly IScheduledJobScheduler _mockScheduledJobScheduler; + private readonly IScheduledJobRepository _mockScheduledJobRepository; + private readonly IScheduledJobExecutionRepository _mockScheduledJobExecutionRepository; + private readonly IValidator _mockValidator; + private readonly RemoveScheduledJobCommandHandler _sut; + private readonly RemoveScheduledJobCommandFixture _removeScheduledJobCommandFixture = new(); + private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new(); + private readonly Guid _userId = Guid.NewGuid(); + + /// + /// Initializes a new instance of the class. + /// + public RemoveScheduledJobCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockDomainEventsQueue = Substitute.For(); + _mockScheduledJobScheduler = Substitute.For(); + _mockScheduledJobRepository = Substitute.For(); + _mockScheduledJobExecutionRepository = Substitute.For(); + + _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); + _mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(true); + + _mockValidator = Substitute.For>(); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new RemoveScheduledJobCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockScheduledJobScheduler, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenScheduledJobExists_ShouldDeleteItAndEnqueueRemovedEvent() + { + // Arrange + RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create(); + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create( + id: command.ScheduledJobId, + scheduleType: ScheduleType.WithIntervalInMinutes, + status: ScheduledJobStatus.Active); + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(Result.From(scheduledJob)); + _mockScheduledJobExecutionRepository.DeleteByScheduledJobIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(Result.Success); + _mockScheduledJobRepository.DeleteByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(Result.Deleted); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Success, result.Value); + await _mockScheduledJobScheduler.Received(1).StopCycleAsync( + Arg.Is(scheduledJobId => scheduledJobId.Value == command.ScheduledJobId), + Arg.Any()); + await _mockScheduledJobExecutionRepository.Received(1).DeleteByScheduledJobIdAsync(command.ScheduledJobId, Arg.Any()); + await _mockScheduledJobRepository.Received(1).DeleteByIdAsync(command.ScheduledJobId, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + _mockDomainEventsQueue.Received(1).Enqueue(Arg.Is(domainEvent => domainEvent is ScheduledJobRemovedDomainEvent)); + } + + [Fact] + public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotDelete() + { + // Arrange + RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([DomainErrors.Scheduling.ScheduledJobNotFound]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized() + { + // Arrange + RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized() + { + // Arrange + RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create(); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenScheduledJobDoesNotExist_ShouldReturnNotFound() + { + // Arrange + RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create(); + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError); + await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenDeleteExecutionsFails_ShouldReturnErrorAndNotDeleteScheduledJob() + { + // Arrange + RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create(); + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create( + id: command.ScheduledJobId, + scheduleType: ScheduleType.WithIntervalInMinutes, + status: ScheduledJobStatus.Active); + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(Result.From(scheduledJob)); + Error error = Error.Failure("Database.Error", "Failed to delete the executions"); + _mockScheduledJobExecutionRepository.DeleteByScheduledJobIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockScheduledJobRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenDeleteScheduledJobFails_ShouldReturnErrorAndNotSaveChanges() + { + // Arrange + RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create(); + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create( + id: command.ScheduledJobId, + scheduleType: ScheduleType.WithIntervalInMinutes, + status: ScheduledJobStatus.Active); + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(Result.From(scheduledJob)); + _mockScheduledJobExecutionRepository.DeleteByScheduledJobIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(Result.Success); + _mockScheduledJobRepository.DeleteByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(DomainErrors.Scheduling.ScheduledJobNotFound); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGettingTheScheduledJobFails_ShouldReturnTheRepositoryError() + { + // Arrange + RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create(); + Error repositoryError = DomainErrors.Scheduling.ScheduledJobNotFound; + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(repositoryError); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(repositoryError, result.FirstError); + await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobExecutionRepository.DidNotReceive().DeleteByScheduledJobIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTheScheduledJobCannotBeConvertedToDomain_ShouldReturnTheMappingError() + { + // Arrange + RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create(); + // An interval schedule whose interval is not positive cannot be converted to its domain object. + ScheduledJobEntity invalidScheduledJob = _scheduledJobEntityFixture.Create( + id: command.ScheduledJobId, + scheduleType: ScheduleType.WithIntervalInMinutes, + intervalMinutes: 0, + status: ScheduledJobStatus.Active); + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(Result.From(invalidScheduledJob)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Scheduling.IntervalMinutesMustBePositive, result.FirstError); + await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobExecutionRepository.DidNotReceive().DeleteByScheduledJobIdAsync(Arg.Any(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandValidatorTests.cs new file mode 100644 index 00000000..344ac140 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandValidatorTests.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob; +using Lumina.Application.Fixtures.Core.Scheduling.Commands.RemoveScheduledJob; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.RemoveScheduledJob; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RemoveScheduledJobCommandValidatorTests +{ + private readonly RemoveScheduledJobCommandValidator _validator = new(); + private readonly RemoveScheduledJobCommandFixture _removeScheduledJobCommandFixture = new(); + + [Fact] + public void Validate_WhenScheduledJobIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create() with { ScheduledJobId = Guid.Empty }; + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Scheduling.ScheduledJobNotFound); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError() + { + // Arrange + RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandlerTests.cs new file mode 100644 index 00000000..453cc88f --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandlerTests.cs @@ -0,0 +1,245 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DomainEvents; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Scheduling.Commands.StartScheduledJob; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Fixtures.Core.Scheduling.Commands.StartScheduledJob; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.StartScheduledJob; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class StartScheduledJobCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly IDomainEventsQueue _mockDomainEventsQueue; + private readonly IScheduledJobRepository _mockScheduledJobRepository; + private readonly IValidator _mockValidator; + private readonly StartScheduledJobCommandHandler _sut; + private readonly StartScheduledJobCommandFixture _startScheduledJobCommandFixture = new(); + private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new(); + private readonly Guid _userId = Guid.NewGuid(); + + /// + /// Initializes a new instance of the class. + /// + public StartScheduledJobCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockDomainEventsQueue = Substitute.For(); + _mockScheduledJobRepository = Substitute.For(); + + _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(true); + + _mockValidator = Substitute.For>(); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new StartScheduledJobCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenScheduledJobIsAdded_ShouldUpdateToActiveAndEnqueueCycleStartedEvent() + { + // Arrange + StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create(); + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create( + id: command.ScheduledJobId, + scheduleType: ScheduleType.WithIntervalInMinutes, + status: ScheduledJobStatus.Added); + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(Result.From(scheduledJob)); + _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(ScheduledJobStatus.Active, result.Value.Status); + await _mockScheduledJobRepository.Received(1).UpdateAsync( + Arg.Is(updatedScheduledJob => updatedScheduledJob.Status == ScheduledJobStatus.Active), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + _mockDomainEventsQueue.Received(1).Enqueue(Arg.Is(domainEvent => domainEvent is ScheduledJobCycleStartedDomainEvent)); + } + + [Fact] + public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotPersist() + { + // Arrange + StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([DomainErrors.Scheduling.ScheduledJobNotFound]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized() + { + // Arrange + StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized() + { + // Arrange + StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create(); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenScheduledJobDoesNotExist_ShouldReturnNotFound() + { + // Arrange + StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create(); + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError); + await _mockScheduledJobRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenScheduledJobCycleAlreadyStarted_ShouldReturnCycleAlreadyStartedError() + { + // Arrange + StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create(); + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create( + id: command.ScheduledJobId, + scheduleType: ScheduleType.WithIntervalInMinutes, + status: ScheduledJobStatus.Active); + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(Result.From(scheduledJob)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Scheduling.ScheduledJobCycleAlreadyStarted, result.FirstError); + await _mockScheduledJobRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUpdateFails_ShouldReturnErrorAndNotSaveChanges() + { + // Arrange + StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create(); + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create( + id: command.ScheduledJobId, + scheduleType: ScheduleType.WithIntervalInMinutes, + status: ScheduledJobStatus.Added); + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(Result.From(scheduledJob)); + _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(DomainErrors.Scheduling.ScheduledJobNotFound); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGettingTheScheduledJobFails_ShouldReturnTheRepositoryError() + { + // Arrange + StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create(); + Error repositoryError = DomainErrors.Scheduling.ScheduledJobNotFound; + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(repositoryError); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(repositoryError, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTheScheduledJobCannotBeConvertedToDomain_ShouldReturnTheMappingError() + { + // Arrange + StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create(); + // An interval schedule whose interval is not positive cannot be converted to its domain object. + ScheduledJobEntity invalidScheduledJob = _scheduledJobEntityFixture.Create( + id: command.ScheduledJobId, + scheduleType: ScheduleType.WithIntervalInMinutes, + intervalMinutes: 0, + status: ScheduledJobStatus.Added); + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(Result.From(invalidScheduledJob)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Scheduling.IntervalMinutesMustBePositive, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandValidatorTests.cs new file mode 100644 index 00000000..9a1b0347 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandValidatorTests.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Scheduling.Commands.StartScheduledJob; +using Lumina.Application.Fixtures.Core.Scheduling.Commands.StartScheduledJob; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.StartScheduledJob; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class StartScheduledJobCommandValidatorTests +{ + private readonly StartScheduledJobCommandValidator _validator = new(); + private readonly StartScheduledJobCommandFixture _startScheduledJobCommandFixture = new(); + + [Fact] + public void Validate_WhenScheduledJobIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create() with { ScheduledJobId = Guid.Empty }; + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Scheduling.ScheduledJobNotFound); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError() + { + // Arrange + StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandlerTests.cs new file mode 100644 index 00000000..7c1d40e1 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandlerTests.cs @@ -0,0 +1,275 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DomainEvents; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Scheduling; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Scheduling.Commands.StopScheduledJob; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Fixtures.Core.Scheduling.Commands.StopScheduledJob; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.StopScheduledJob; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class StopScheduledJobCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly IDomainEventsQueue _mockDomainEventsQueue; + private readonly IScheduledJobScheduler _mockScheduledJobScheduler; + private readonly IScheduledJobRepository _mockScheduledJobRepository; + private readonly IValidator _mockValidator; + private readonly StopScheduledJobCommandHandler _sut; + private readonly StopScheduledJobCommandFixture _stopScheduledJobCommandFixture = new(); + private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new(); + private readonly Guid _userId = Guid.NewGuid(); + + /// + /// Initializes a new instance of the class. + /// + public StopScheduledJobCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockDomainEventsQueue = Substitute.For(); + _mockScheduledJobScheduler = Substitute.For(); + _mockScheduledJobRepository = Substitute.For(); + + _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(true); + + _mockValidator = Substitute.For>(); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new StopScheduledJobCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockScheduledJobScheduler, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenScheduledJobIsActive_ShouldUpdateToAddedAndStopCycleInScheduler() + { + // Arrange + StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create(); + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create( + id: command.ScheduledJobId, + scheduleType: ScheduleType.WithIntervalInMinutes, + status: ScheduledJobStatus.Active); + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(Result.From(scheduledJob)); + _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(ScheduledJobStatus.Added, result.Value.Status); + await _mockScheduledJobRepository.Received(1).UpdateAsync( + Arg.Is(updatedScheduledJob => updatedScheduledJob.Status == ScheduledJobStatus.Added), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockScheduledJobScheduler.Received(1).StopCycleAsync( + Arg.Is(scheduledJobId => scheduledJobId.Value == command.ScheduledJobId), + Arg.Any()); + _mockDomainEventsQueue.Received(1).Enqueue(Arg.Is(domainEvent => domainEvent is ScheduledJobCycleStoppedDomainEvent)); + } + + [Fact] + public async Task HandleAsync_WhenScheduledJobIsRunning_ShouldEnqueueExecutionStoppedEvent() + { + // Arrange + StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create(); + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create( + id: command.ScheduledJobId, + scheduleType: ScheduleType.WithIntervalInMinutes, + status: ScheduledJobStatus.Running, + lastStartedOnUtc: DateTime.UtcNow.AddMinutes(-10)); + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(Result.From(scheduledJob)); + _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(ScheduledJobStatus.Added, result.Value.Status); + _mockDomainEventsQueue.Received(1).Enqueue(Arg.Is(domainEvent => domainEvent is ScheduledJobExecutionStoppedDomainEvent)); + await _mockScheduledJobScheduler.Received(1).StopCycleAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotPersist() + { + // Arrange + StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([DomainErrors.Scheduling.ScheduledJobNotFound]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized() + { + // Arrange + StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized() + { + // Arrange + StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create(); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenScheduledJobDoesNotExist_ShouldReturnNotFound() + { + // Arrange + StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create(); + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError); + await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenScheduledJobCycleWasNeverStarted_ShouldReturnNotStartedError() + { + // Arrange + StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create(); + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create( + id: command.ScheduledJobId, + scheduleType: ScheduleType.WithIntervalInMinutes, + status: ScheduledJobStatus.Added); + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(Result.From(scheduledJob)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotStarted, result.FirstError); + await _mockScheduledJobRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUpdateFails_ShouldReturnErrorAndNotStopCycleInScheduler() + { + // Arrange + StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create(); + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create( + id: command.ScheduledJobId, + scheduleType: ScheduleType.WithIntervalInMinutes, + status: ScheduledJobStatus.Active); + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(Result.From(scheduledJob)); + _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(DomainErrors.Scheduling.ScheduledJobNotFound); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGettingTheScheduledJobFails_ShouldReturnTheRepositoryError() + { + // Arrange + StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create(); + Error repositoryError = DomainErrors.Scheduling.ScheduledJobNotFound; + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(repositoryError); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(repositoryError, result.FirstError); + await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTheScheduledJobCannotBeConvertedToDomain_ShouldReturnTheMappingError() + { + // Arrange + StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create(); + // An interval schedule whose interval is not positive cannot be converted to its domain object. + ScheduledJobEntity invalidScheduledJob = _scheduledJobEntityFixture.Create( + id: command.ScheduledJobId, + scheduleType: ScheduleType.WithIntervalInMinutes, + intervalMinutes: 0, + status: ScheduledJobStatus.Active); + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(Result.From(invalidScheduledJob)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Scheduling.IntervalMinutesMustBePositive, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandValidatorTests.cs new file mode 100644 index 00000000..416b7fd8 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandValidatorTests.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Scheduling.Commands.StopScheduledJob; +using Lumina.Application.Fixtures.Core.Scheduling.Commands.StopScheduledJob; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.StopScheduledJob; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class StopScheduledJobCommandValidatorTests +{ + private readonly StopScheduledJobCommandValidator _validator = new(); + private readonly StopScheduledJobCommandFixture _stopScheduledJobCommandFixture = new(); + + [Fact] + public void Validate_WhenScheduledJobIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create() with { ScheduledJobId = Guid.Empty }; + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Scheduling.ScheduledJobNotFound); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError() + { + // Arrange + StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandHandlerTests.cs new file mode 100644 index 00000000..56b302ff --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandHandlerTests.cs @@ -0,0 +1,152 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences; +using Lumina.Application.Fixtures.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateSchedulerDisplayPreferencesCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ISchedulerDisplayPreferencesRepository _mockSchedulerDisplayPreferencesRepository; + private readonly IValidator _mockValidator; + private readonly UpdateSchedulerDisplayPreferencesCommandHandler _sut; + private readonly UpdateSchedulerDisplayPreferencesCommandFixture _updateSchedulerDisplayPreferencesCommandFixture = new(); + private readonly Guid _userId = Guid.NewGuid(); + + /// + /// Initializes a new instance of the class. + /// + public UpdateSchedulerDisplayPreferencesCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockSchedulerDisplayPreferencesRepository = Substitute.For(); + + _mockUnitOfWork.SchedulerDisplayPreferencesRepository.Returns(_mockSchedulerDisplayPreferencesRepository); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(true); + + _mockValidator = Substitute.For>(); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new UpdateSchedulerDisplayPreferencesCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenCommandIsValid_ShouldUpsertDisplayPreferencesAndReturnUpdated() + { + // Arrange + UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create( + jobTypeFilter: ScheduledTaskType.ScanMediaLibraries, + displayTimeSpan: 30, + displayTimeUnit: SchedulerDisplayTimeUnit.Minutes); + _mockSchedulerDisplayPreferencesRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + await _mockSchedulerDisplayPreferencesRepository.Received(1).UpsertAsync( + Arg.Is(preferences => + preferences.UserId == _userId && + preferences.JobTypeFilter == ScheduledTaskType.ScanMediaLibraries && + preferences.DisplayTimeSpan == 30 && + preferences.DisplayTimeUnit == SchedulerDisplayTimeUnit.Minutes), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotPersist() + { + // Arrange + UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create(displayTimeSpan: 0); + _mockValidator.Validate(Arg.Any()) + .Returns([DomainErrors.Scheduling.SchedulerDisplayTimeSpanMustBePositive]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Scheduling.SchedulerDisplayTimeSpanMustBePositive, result.FirstError); + await _mockSchedulerDisplayPreferencesRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized() + { + // Arrange + UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockSchedulerDisplayPreferencesRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized() + { + // Arrange + UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create(); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockSchedulerDisplayPreferencesRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUpsertFails_ShouldReturnErrorAndNotSaveChanges() + { + // Arrange + UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to upsert the display preferences"); + _mockSchedulerDisplayPreferencesRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandValidatorTests.cs new file mode 100644 index 00000000..f81c2ec3 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandValidatorTests.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences; +using Lumina.Application.Fixtures.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateSchedulerDisplayPreferencesCommandValidatorTests +{ + private readonly UpdateSchedulerDisplayPreferencesCommandValidator _validator = new(); + private readonly UpdateSchedulerDisplayPreferencesCommandFixture _updateSchedulerDisplayPreferencesCommandFixture = new(); + + [Theory] + [InlineData(0)] // display time span of zero + [InlineData(-1)] // negative display time span + [InlineData(-100)] // negative display time span far from zero + public void Validate_WhenDisplayTimeSpanIsNotPositive_ShouldHaveValidationError(int displayTimeSpan) + { + // Arrange + UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create(displayTimeSpan: displayTimeSpan); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Scheduling.SchedulerDisplayTimeSpanMustBePositive); + } + + [Theory] + [InlineData(1)] // minimal positive display time span + [InlineData(10)] // default display time span + [InlineData(1440)] // a day expressed in minutes + public void Validate_WhenDisplayTimeSpanIsPositive_ShouldNotHaveValidationError(int displayTimeSpan) + { + // Arrange + UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create(displayTimeSpan: displayTimeSpan); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Scheduling.SchedulerDisplayTimeSpanMustBePositive); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError() + { + // Arrange + UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobAddedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobAddedDomainEventHandlerTests.cs new file mode 100644 index 00000000..a26df0e4 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobAddedDomainEventHandlerTests.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Core.Scheduling.Events; +using Lumina.Application.Core.Scheduling.Notifications; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Exceptions; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.Scheduling.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobAddedDomainEventHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IScheduledJobNotifier _mockScheduledJobNotifier; + private readonly IScheduledJobRepository _mockScheduledJobRepository; + private readonly ScheduledJobAddedDomainEventHandler _sut; + private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new(); + private readonly ScheduledJobAddedDomainEventFixture _scheduledJobAddedDomainEventFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ScheduledJobAddedDomainEventHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockScheduledJobNotifier = Substitute.For(); + _mockScheduledJobRepository = Substitute.For(); + + _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); + _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + + _sut = new ScheduledJobAddedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork); + } + + [Fact] + public async Task HandleAsync_WhenScheduledJobsAreLoaded_ShouldNotifyTheCurrentScheduledJobs() + { + // Arrange + ScheduledJobAddedDomainEvent domainEvent = _scheduledJobAddedDomainEventFixture.Create(); + ScheduledJobEntity scheduledJob1 = _scheduledJobEntityFixture.Create(name: "Job 1"); + ScheduledJobEntity scheduledJob2 = _scheduledJobEntityFixture.Create(name: "Job 2"); + _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([scheduledJob1, scheduledJob2])); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + await _mockScheduledJobNotifier.Received(1).SendScheduledJobsAsync( + Arg.Is>(scheduledJobs => scheduledJobs.Count == 2), + Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetAllScheduledJobsFails_ShouldThrowEventualConsistencyException() + { + // Arrange + ScheduledJobAddedDomainEvent domainEvent = _scheduledJobAddedDomainEventFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs"); + _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockScheduledJobNotifier.DidNotReceive().SendScheduledJobsAsync(Arg.Any>(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobCycleStartedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobCycleStartedDomainEventHandlerTests.cs new file mode 100644 index 00000000..1a19fd47 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobCycleStartedDomainEventHandlerTests.cs @@ -0,0 +1,82 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Scheduling; +using Lumina.Application.Core.Scheduling.Events; +using Lumina.Application.Core.Scheduling.Notifications; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Exceptions; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.Scheduling.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobCycleStartedDomainEventHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IScheduledJobNotifier _mockScheduledJobNotifier; + private readonly IScheduledJobScheduler _mockScheduledJobScheduler; + private readonly IScheduledJobRepository _mockScheduledJobRepository; + private readonly ScheduledJobCycleStartedDomainEventHandler _sut; + private readonly ScheduledJobCycleStartedDomainEventFixture _scheduledJobCycleStartedDomainEventFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ScheduledJobCycleStartedDomainEventHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockScheduledJobNotifier = Substitute.For(); + _mockScheduledJobScheduler = Substitute.For(); + _mockScheduledJobRepository = Substitute.For(); + + _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); + _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + + _sut = new ScheduledJobCycleStartedDomainEventHandler(_mockScheduledJobNotifier, _mockScheduledJobScheduler, _mockUnitOfWork); + } + + [Fact] + public async Task HandleAsync_WhenScheduledJobsAreLoaded_ShouldStartTheCycleInTheSchedulerAndNotify() + { + // Arrange + ScheduledJobCycleStartedDomainEvent domainEvent = _scheduledJobCycleStartedDomainEventFixture.Create(); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + await _mockScheduledJobScheduler.Received(1).StartCycleAsync(domainEvent.ScheduledJobId, Arg.Any()); + await _mockScheduledJobNotifier.Received(1).SendScheduledJobsAsync(Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetAllScheduledJobsFails_ShouldThrowEventualConsistencyException() + { + // Arrange + ScheduledJobCycleStartedDomainEvent domainEvent = _scheduledJobCycleStartedDomainEventFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs"); + _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockScheduledJobNotifier.DidNotReceive().SendScheduledJobsAsync(Arg.Any>(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobCycleStoppedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobCycleStoppedDomainEventHandlerTests.cs new file mode 100644 index 00000000..2de58f22 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobCycleStoppedDomainEventHandlerTests.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Core.Scheduling.Events; +using Lumina.Application.Core.Scheduling.Notifications; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Exceptions; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.Scheduling.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobCycleStoppedDomainEventHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IScheduledJobNotifier _mockScheduledJobNotifier; + private readonly IScheduledJobRepository _mockScheduledJobRepository; + private readonly ScheduledJobCycleStoppedDomainEventHandler _sut; + private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new(); + private readonly ScheduledJobCycleStoppedDomainEventFixture _scheduledJobCycleStoppedDomainEventFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ScheduledJobCycleStoppedDomainEventHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockScheduledJobNotifier = Substitute.For(); + _mockScheduledJobRepository = Substitute.For(); + + _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); + _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + + _sut = new ScheduledJobCycleStoppedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork); + } + + [Fact] + public async Task HandleAsync_WhenScheduledJobsAreLoaded_ShouldNotifyTheCurrentScheduledJobs() + { + // Arrange + ScheduledJobCycleStoppedDomainEvent domainEvent = _scheduledJobCycleStoppedDomainEventFixture.Create(); + ScheduledJobEntity stoppedJob = _scheduledJobEntityFixture.Create(name: "Stopped job", status: Lumina.Domain.SharedKernel.Common.Enums.Scheduling.ScheduledJobStatus.Added); + _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([stoppedJob])); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + await _mockScheduledJobNotifier.Received(1).SendScheduledJobsAsync( + Arg.Is>(scheduledJobs => scheduledJobs.Count == 1), + Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetAllScheduledJobsFails_ShouldThrowEventualConsistencyException() + { + // Arrange + ScheduledJobCycleStoppedDomainEvent domainEvent = _scheduledJobCycleStoppedDomainEventFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs"); + _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockScheduledJobNotifier.DidNotReceive().SendScheduledJobsAsync(Arg.Any>(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandlerTests.cs new file mode 100644 index 00000000..9f0ef999 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandlerTests.cs @@ -0,0 +1,200 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Core.Scheduling.Events; +using Lumina.Application.Core.Scheduling.Notifications; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Exceptions; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.Scheduling.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobExecutionCompletedDomainEventHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IScheduledJobNotifier _mockScheduledJobNotifier; + private readonly IScheduledJobRepository _mockScheduledJobRepository; + private readonly IScheduledJobExecutionRepository _mockScheduledJobExecutionRepository; + private readonly ScheduledJobExecutionCompletedDomainEventHandler _sut; + private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new(); + private readonly ScheduledJobExecutionEntityFixture _scheduledJobExecutionEntityFixture = new(); + private readonly ScheduledJobExecutionCompletedDomainEventFixture _scheduledJobExecutionCompletedDomainEventFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ScheduledJobExecutionCompletedDomainEventHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockScheduledJobNotifier = Substitute.For(); + _mockScheduledJobRepository = Substitute.For(); + _mockScheduledJobExecutionRepository = Substitute.For(); + + _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); + _mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository); + _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); + _mockScheduledJobExecutionRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); + _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + + _sut = new ScheduledJobExecutionCompletedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork); + } + + [Theory] + [InlineData(true, ScheduledJobStatus.Active)] // a cycle run returns the scheduled job to its active status + [InlineData(false, ScheduledJobStatus.Completed)] // a one time execution completes the scheduled job + public async Task HandleAsync_WhenScheduledJobAndExecutionExist_ShouldUpdateBothAndNotify(bool isCycleRun, ScheduledJobStatus expectedStatus) + { + // Arrange + DateTime completedOnUtc = DateTime.UtcNow; + ScheduledJobExecutionCompletedDomainEvent domainEvent = _scheduledJobExecutionCompletedDomainEventFixture.Create(isCycleRun: isCycleRun, completedOnUtc: completedOnUtc); + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create( + id: domainEvent.ScheduledJobId.Value, + status: ScheduledJobStatus.Running, + lastStartedOnUtc: completedOnUtc.AddMinutes(-5)); + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + .Returns(Result.From(scheduledJob)); + ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create( + id: domainEvent.RunId, + scheduledJobId: scheduledJob.Id, + isCycleRun: isCycleRun, + completedOnUtc: null); + _mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, Arg.Any()) + .Returns(Result.From(execution)); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + await _mockScheduledJobRepository.Received(1).UpdateAsync( + Arg.Is(updatedScheduledJob => + updatedScheduledJob.Status == expectedStatus && + updatedScheduledJob.LastCompletedOnUtc == completedOnUtc), + Arg.Any()); + await _mockScheduledJobExecutionRepository.Received(1).UpdateAsync( + Arg.Is(updatedExecution => updatedExecution.CompletedOnUtc == completedOnUtc), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockScheduledJobNotifier.Received(1).SendScheduledJobsAsync(Arg.Any>(), Arg.Any()); + await _mockScheduledJobNotifier.Received(1).SendScheduledJobExecutionCompletedAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenScheduledJobDoesNotExist_ShouldThrowEventualConsistencyException() + { + // Arrange + ScheduledJobExecutionCompletedDomainEvent domainEvent = _scheduledJobExecutionCompletedDomainEventFixture.Create(isCycleRun: true); + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + .Returns(Result.From(null)); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(Errors.Scheduling.ScheduledJobNotFound, exception.EventualConsistencyError); + await _mockScheduledJobExecutionRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUpdateScheduledJobFails_ShouldThrowEventualConsistencyException() + { + // Arrange + ScheduledJobExecutionCompletedDomainEvent domainEvent = _scheduledJobExecutionCompletedDomainEventFixture.Create(isCycleRun: true); + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(id: domainEvent.ScheduledJobId.Value, status: ScheduledJobStatus.Running); + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + .Returns(Result.From(scheduledJob)); + Error error = Error.Failure("Database.Error", "Failed to update the scheduled job"); + _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockScheduledJobExecutionRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenExecutionDoesNotExist_ShouldThrowEventualConsistencyException() + { + // Arrange + ScheduledJobExecutionCompletedDomainEvent domainEvent = _scheduledJobExecutionCompletedDomainEventFixture.Create(isCycleRun: true); + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(id: domainEvent.ScheduledJobId.Value, status: ScheduledJobStatus.Running); + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + .Returns(Result.From(scheduledJob)); + _mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, Arg.Any()) + .Returns(Result.From(null)); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(Errors.Scheduling.ScheduledJobExecutionNotFound, exception.EventualConsistencyError); + await _mockScheduledJobExecutionRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUpdateExecutionFails_ShouldThrowEventualConsistencyException() + { + // Arrange + ScheduledJobExecutionCompletedDomainEvent domainEvent = _scheduledJobExecutionCompletedDomainEventFixture.Create(isCycleRun: true); + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(id: domainEvent.ScheduledJobId.Value, status: ScheduledJobStatus.Running); + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + .Returns(Result.From(scheduledJob)); + ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create(id: domainEvent.RunId); + _mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, Arg.Any()) + .Returns(Result.From(execution)); + Error error = Error.Failure("Database.Error", "Failed to update the execution"); + _mockScheduledJobExecutionRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetAllScheduledJobsFails_ShouldThrowEventualConsistencyException() + { + // Arrange + ScheduledJobExecutionCompletedDomainEvent domainEvent = _scheduledJobExecutionCompletedDomainEventFixture.Create(isCycleRun: true); + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(id: domainEvent.ScheduledJobId.Value, status: ScheduledJobStatus.Running); + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + .Returns(Result.From(scheduledJob)); + ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create(id: domainEvent.RunId); + _mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, Arg.Any()) + .Returns(Result.From(execution)); + Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs"); + _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockScheduledJobNotifier.DidNotReceive().SendScheduledJobExecutionCompletedAsync(Arg.Any(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandlerTests.cs new file mode 100644 index 00000000..8613b765 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandlerTests.cs @@ -0,0 +1,191 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Core.Scheduling.Events; +using Lumina.Application.Core.Scheduling.Notifications; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Exceptions; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.Scheduling.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobExecutionStartedDomainEventHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IScheduledJobNotifier _mockScheduledJobNotifier; + private readonly IScheduledJobRepository _mockScheduledJobRepository; + private readonly IScheduledJobExecutionRepository _mockScheduledJobExecutionRepository; + private readonly ScheduledJobExecutionStartedDomainEventHandler _sut; + private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new(); + private readonly ScheduledJobExecutionEntityFixture _scheduledJobExecutionEntityFixture = new(); + private readonly ScheduledJobExecutionStartedDomainEventFixture _scheduledJobExecutionStartedDomainEventFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ScheduledJobExecutionStartedDomainEventHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockScheduledJobNotifier = Substitute.For(); + _mockScheduledJobRepository = Substitute.For(); + _mockScheduledJobExecutionRepository = Substitute.For(); + + _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); + _mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository); + _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); + _mockScheduledJobExecutionRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Created); + _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + + _sut = new ScheduledJobExecutionStartedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork); + } + + [Fact] + public async Task HandleAsync_WhenScheduledJobExists_ShouldUpdateItsStatusAndInsertTheExecution() + { + // Arrange + DateTime startedOnUtc = DateTime.UtcNow.AddMinutes(-1); + ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create(startedOnUtc: startedOnUtc); + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create( + id: domainEvent.ScheduledJobId.Value, + taskType: domainEvent.TaskType, + scheduleType: ScheduleType.WithIntervalInMinutes, + status: ScheduledJobStatus.Active); + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + .Returns(Result.From(scheduledJob)); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + await _mockScheduledJobRepository.Received(1).UpdateAsync( + Arg.Is(updatedScheduledJob => + updatedScheduledJob.Status == ScheduledJobStatus.Running && + updatedScheduledJob.LastStartedOnUtc == startedOnUtc), + Arg.Any()); + await _mockScheduledJobExecutionRepository.Received(1).InsertAsync( + Arg.Is(execution => + execution.Id == domainEvent.RunId && + execution.ScheduledJobId == scheduledJob.Id && + execution.TaskType == domainEvent.TaskType && + execution.IsCycleRun == domainEvent.IsCycleRun && + execution.StartedOnUtc == startedOnUtc && + execution.CompletedOnUtc == null), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockScheduledJobNotifier.Received(1).SendScheduledJobsAsync(Arg.Any>(), Arg.Any()); + await _mockScheduledJobNotifier.Received(1).SendScheduledJobExecutionStartedAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetByIdReturnsError_ShouldThrowEventualConsistencyException() + { + // Arrange + ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to get the scheduled job"); + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()).Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockScheduledJobExecutionRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenScheduledJobDoesNotExist_ShouldThrowEventualConsistencyException() + { + // Arrange + ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create(); + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + .Returns(Result.From(null)); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(Errors.Scheduling.ScheduledJobNotFound, exception.EventualConsistencyError); + } + + [Fact] + public async Task HandleAsync_WhenUpdateFails_ShouldThrowEventualConsistencyException() + { + // Arrange + ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create(); + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create( + id: domainEvent.ScheduledJobId.Value, + status: ScheduledJobStatus.Active); + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + .Returns(Result.From(scheduledJob)); + Error error = Error.Failure("Database.Error", "Failed to update the scheduled job"); + _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockScheduledJobExecutionRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenInsertExecutionFails_ShouldThrowEventualConsistencyException() + { + // Arrange + ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create(); + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(id: domainEvent.ScheduledJobId.Value); + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + .Returns(Result.From(scheduledJob)); + Error error = Error.Failure("Database.Error", "Failed to insert the execution"); + _mockScheduledJobExecutionRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetAllScheduledJobsFails_ShouldThrowEventualConsistencyException() + { + // Arrange + ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create(); + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(id: domainEvent.ScheduledJobId.Value); + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + .Returns(Result.From(scheduledJob)); + Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs"); + _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockScheduledJobNotifier.DidNotReceive().SendScheduledJobExecutionStartedAsync(Arg.Any(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandlerTests.cs new file mode 100644 index 00000000..52c0b749 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandlerTests.cs @@ -0,0 +1,153 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Core.Scheduling.Events; +using Lumina.Application.Core.Scheduling.Notifications; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Exceptions; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.Scheduling.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobExecutionStoppedDomainEventHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IScheduledJobNotifier _mockScheduledJobNotifier; + private readonly IScheduledJobRepository _mockScheduledJobRepository; + private readonly IScheduledJobExecutionRepository _mockScheduledJobExecutionRepository; + private readonly ScheduledJobExecutionStoppedDomainEventHandler _sut; + private readonly ScheduledJobExecutionEntityFixture _scheduledJobExecutionEntityFixture = new(); + private readonly ScheduledJobExecutionStoppedDomainEventFixture _scheduledJobExecutionStoppedDomainEventFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ScheduledJobExecutionStoppedDomainEventHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockScheduledJobNotifier = Substitute.For(); + _mockScheduledJobRepository = Substitute.For(); + _mockScheduledJobExecutionRepository = Substitute.For(); + + _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); + _mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository); + _mockScheduledJobExecutionRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); + _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + + _sut = new ScheduledJobExecutionStoppedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork); + } + + [Fact] + public async Task HandleAsync_WhenOpenExecutionExists_ShouldCloseItAndNotifyScheduledJobs() + { + // Arrange + DateTime occurredOnUtc = DateTime.UtcNow; + ScheduledJobExecutionStoppedDomainEvent domainEvent = _scheduledJobExecutionStoppedDomainEventFixture.Create(occurredOnUtc: occurredOnUtc); + ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create( + scheduledJobId: domainEvent.ScheduledJobId.Value, + completedOnUtc: null); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + .Returns(Result.From(openExecution)); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + await _mockScheduledJobExecutionRepository.Received(1).UpdateAsync( + Arg.Is(updatedExecution => updatedExecution.CompletedOnUtc == occurredOnUtc), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockScheduledJobNotifier.Received(1).SendScheduledJobsAsync(Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenNoOpenExecutionExists_ShouldOnlyNotifyScheduledJobs() + { + // Arrange + ScheduledJobExecutionStoppedDomainEvent domainEvent = _scheduledJobExecutionStoppedDomainEventFixture.Create(); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + .Returns(Result.From(null)); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + await _mockScheduledJobExecutionRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockScheduledJobNotifier.Received(1).SendScheduledJobsAsync(Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetOpenExecutionFails_ShouldThrowEventualConsistencyException() + { + // Arrange + ScheduledJobExecutionStoppedDomainEvent domainEvent = _scheduledJobExecutionStoppedDomainEventFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to get the open execution"); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + .Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockScheduledJobNotifier.DidNotReceive().SendScheduledJobsAsync(Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUpdateExecutionFails_ShouldThrowEventualConsistencyException() + { + // Arrange + ScheduledJobExecutionStoppedDomainEvent domainEvent = _scheduledJobExecutionStoppedDomainEventFixture.Create(); + ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create( + scheduledJobId: domainEvent.ScheduledJobId.Value, + completedOnUtc: null); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + .Returns(Result.From(openExecution)); + Error error = Error.Failure("Database.Error", "Failed to update the execution"); + _mockScheduledJobExecutionRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockScheduledJobNotifier.DidNotReceive().SendScheduledJobsAsync(Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetAllScheduledJobsFails_ShouldThrowEventualConsistencyException() + { + // Arrange + ScheduledJobExecutionStoppedDomainEvent domainEvent = _scheduledJobExecutionStoppedDomainEventFixture.Create(); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + .Returns(Result.From(null)); + Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs"); + _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockScheduledJobNotifier.DidNotReceive().SendScheduledJobsAsync(Arg.Any>(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobFiredDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobFiredDomainEventHandlerTests.cs new file mode 100644 index 00000000..1da8bd87 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobFiredDomainEventHandlerTests.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Scheduling; +using Lumina.Application.Core.Scheduling.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.Scheduling.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobFiredDomainEventHandlerTests +{ + private readonly IScheduledJobScheduler _mockScheduledJobScheduler; + private readonly ScheduledJobFiredDomainEventHandler _sut; + private readonly ScheduledJobFiredDomainEventFixture _scheduledJobFiredDomainEventFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ScheduledJobFiredDomainEventHandlerTests() + { + _mockScheduledJobScheduler = Substitute.For(); + _sut = new ScheduledJobFiredDomainEventHandler(_mockScheduledJobScheduler); + } + + [Fact] + public async Task HandleAsync_WhenFiredEventIsHandled_ShouldRunTheTaskOnceInTheScheduler() + { + // Arrange + ScheduledJobFiredDomainEvent domainEvent = _scheduledJobFiredDomainEventFixture.Create(); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + await _mockScheduledJobScheduler.Received(1).RunOnceAsync(domainEvent.ScheduledJobId, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobRemovedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobRemovedDomainEventHandlerTests.cs new file mode 100644 index 00000000..54ed5c7c --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobRemovedDomainEventHandlerTests.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Core.Scheduling.Events; +using Lumina.Application.Core.Scheduling.Notifications; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Exceptions; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.Scheduling.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobRemovedDomainEventHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IScheduledJobNotifier _mockScheduledJobNotifier; + private readonly IScheduledJobRepository _mockScheduledJobRepository; + private readonly ScheduledJobRemovedDomainEventHandler _sut; + private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new(); + private readonly ScheduledJobRemovedDomainEventFixture _scheduledJobRemovedDomainEventFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ScheduledJobRemovedDomainEventHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockScheduledJobNotifier = Substitute.For(); + _mockScheduledJobRepository = Substitute.For(); + + _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); + _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + + _sut = new ScheduledJobRemovedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork); + } + + [Fact] + public async Task HandleAsync_WhenScheduledJobsAreLoaded_ShouldNotifyTheCurrentScheduledJobs() + { + // Arrange + ScheduledJobRemovedDomainEvent domainEvent = _scheduledJobRemovedDomainEventFixture.Create(); + ScheduledJobEntity remainingJob = _scheduledJobEntityFixture.Create(name: "Remaining job"); + _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([remainingJob])); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + await _mockScheduledJobNotifier.Received(1).SendScheduledJobsAsync( + Arg.Is>(scheduledJobs => scheduledJobs.Count == 1), + Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetAllScheduledJobsFails_ShouldThrowEventualConsistencyException() + { + // Arrange + ScheduledJobRemovedDomainEvent domainEvent = _scheduledJobRemovedDomainEventFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs"); + _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockScheduledJobNotifier.DidNotReceive().SendScheduledJobsAsync(Arg.Any>(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQueryHandlerTests.cs new file mode 100644 index 00000000..45ed8366 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQueryHandlerTests.cs @@ -0,0 +1,161 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Core.Scheduling.Queries.GetScheduledJobHistory; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Fixtures.Core.Scheduling.Queries.GetScheduledJobHistory; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Scheduling.Queries.GetScheduledJobHistory; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetScheduledJobHistoryQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly IScheduledJobExecutionRepository _mockScheduledJobExecutionRepository; + private readonly GetScheduledJobHistoryQueryHandler _sut; + private readonly GetScheduledJobHistoryQueryFixture _getScheduledJobHistoryQueryFixture = new(); + private readonly ScheduledJobExecutionEntityFixture _scheduledJobExecutionEntityFixture = new(); + private readonly Guid _userId = Guid.NewGuid(); + + /// + /// Initializes a new instance of the class. + /// + public GetScheduledJobHistoryQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockScheduledJobExecutionRepository = Substitute.For(); + + _mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(true); + + _sut = new GetScheduledJobHistoryQueryHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork); + } + + [Fact] + public async Task HandleAsync_WhenExecutionsExistInTheRequestedRange_ShouldReturnThemAsResponses() + { + // Arrange + GetScheduledJobHistoryQuery query = _getScheduledJobHistoryQueryFixture.Create(); + ScheduledJobExecutionEntity execution1 = _scheduledJobExecutionEntityFixture.Create(startedOnUtc: query.From); + ScheduledJobExecutionEntity execution2 = _scheduledJobExecutionEntityFixture.Create(startedOnUtc: query.From!.Value.AddMinutes(1)); + _mockScheduledJobExecutionRepository.GetByTimeRangeAsync(query.From!.Value, query.To!.Value, Arg.Any()) + .Returns(Result.From>([execution1, execution2])); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Count()); + Assert.Contains(result.Value, execution => execution.Id == execution1.Id); + Assert.Contains(result.Value, execution => execution.Id == execution2.Id); + } + + [Fact] + public async Task HandleAsync_WhenNoExecutionsExist_ShouldReturnEmptyCollection() + { + // Arrange + GetScheduledJobHistoryQuery query = _getScheduledJobHistoryQueryFixture.Create(); + _mockScheduledJobExecutionRepository.GetByTimeRangeAsync(query.From!.Value, query.To!.Value, Arg.Any()) + .Returns(Result.From>([])); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task HandleAsync_WhenBoundsAreNotProvided_ShouldDefaultToThePastDay() + { + // Arrange + GetScheduledJobHistoryQuery query = _getScheduledJobHistoryQueryFixture.Create(includeFrom: false, includeTo: false); + DateTime beforeCall = DateTime.UtcNow; + _mockScheduledJobExecutionRepository.GetByTimeRangeAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + DateTime afterCall = DateTime.UtcNow; + + // Assert + Assert.False(result.IsFailure); + await _mockScheduledJobExecutionRepository.Received(1).GetByTimeRangeAsync( + Arg.Is(fromUtc => fromUtc <= afterCall && fromUtc >= beforeCall.AddDays(-1)), + Arg.Is(toUtc => toUtc >= beforeCall && toUtc <= afterCall), + Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized() + { + // Arrange + GetScheduledJobHistoryQuery query = _getScheduledJobHistoryQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockScheduledJobExecutionRepository.DidNotReceive().GetByTimeRangeAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized() + { + // Arrange + GetScheduledJobHistoryQuery query = _getScheduledJobHistoryQueryFixture.Create(); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockScheduledJobExecutionRepository.DidNotReceive().GetByTimeRangeAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetByTimeRangeReturnsError_ShouldReturnError() + { + // Arrange + GetScheduledJobHistoryQuery query = _getScheduledJobHistoryQueryFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to get the execution history"); + _mockScheduledJobExecutionRepository.GetByTimeRangeAsync(query.From!.Value, query.To!.Value, Arg.Any()) + .Returns(error); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQueryHandlerTests.cs new file mode 100644 index 00000000..146499ae --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQueryHandlerTests.cs @@ -0,0 +1,132 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Core.Scheduling.Queries.GetScheduledJobs; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Scheduling.Queries.GetScheduledJobs; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetScheduledJobsQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly IScheduledJobRepository _mockScheduledJobRepository; + private readonly GetScheduledJobsQueryHandler _sut; + private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new(); + private readonly Guid _userId = Guid.NewGuid(); + + /// + /// Initializes a new instance of the class. + /// + public GetScheduledJobsQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockScheduledJobRepository = Substitute.For(); + + _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(true); + + _sut = new GetScheduledJobsQueryHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork); + } + + [Fact] + public async Task HandleAsync_WhenScheduledJobsExist_ShouldReturnAllOfThemAsResponses() + { + // Arrange + ScheduledJobEntity scheduledJob1 = _scheduledJobEntityFixture.Create(name: "Job 1"); + ScheduledJobEntity scheduledJob2 = _scheduledJobEntityFixture.Create(name: "Job 2"); + _mockScheduledJobRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From>([scheduledJob1, scheduledJob2])); + + // Act + Result> result = await _sut.HandleAsync(new GetScheduledJobsQuery(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Count()); + Assert.Contains(result.Value, scheduledJob => scheduledJob.Id == scheduledJob1.Id && scheduledJob.Name == "Job 1"); + Assert.Contains(result.Value, scheduledJob => scheduledJob.Id == scheduledJob2.Id && scheduledJob.Name == "Job 2"); + } + + [Fact] + public async Task HandleAsync_WhenNoScheduledJobsExist_ShouldReturnEmptyCollection() + { + // Arrange + _mockScheduledJobRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From>([])); + + // Act + Result> result = await _sut.HandleAsync(new GetScheduledJobsQuery(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized() + { + // Arrange + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result> result = await _sut.HandleAsync(new GetScheduledJobsQuery(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockScheduledJobRepository.DidNotReceive().GetAllAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized() + { + // Arrange + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); + + // Act + Result> result = await _sut.HandleAsync(new GetScheduledJobsQuery(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockScheduledJobRepository.DidNotReceive().GetAllAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetAllReturnsError_ShouldReturnError() + { + // Arrange + Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs"); + _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(error); + + // Act + Result> result = await _sut.HandleAsync(new GetScheduledJobsQuery(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesQueryHandlerTests.cs new file mode 100644 index 00000000..4fa22ff1 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesQueryHandlerTests.cs @@ -0,0 +1,142 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Core.Scheduling.Queries.GetSchedulerDisplayPreferences; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Scheduling.Queries.GetSchedulerDisplayPreferences; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetSchedulerDisplayPreferencesQueryHandlerTests +{ + private const int DEFAULT_DISPLAY_TIME_SPAN = 10; + private const SchedulerDisplayTimeUnit DEFAULT_DISPLAY_TIME_UNIT = SchedulerDisplayTimeUnit.Minutes; + + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ISchedulerDisplayPreferencesRepository _mockSchedulerDisplayPreferencesRepository; + private readonly GetSchedulerDisplayPreferencesQueryHandler _sut; + private readonly SchedulerDisplayPreferencesEntityFixture _schedulerDisplayPreferencesEntityFixture = new(); + private readonly Guid _userId = Guid.NewGuid(); + + /// + /// Initializes a new instance of the class. + /// + public GetSchedulerDisplayPreferencesQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockSchedulerDisplayPreferencesRepository = Substitute.For(); + + _mockUnitOfWork.SchedulerDisplayPreferencesRepository.Returns(_mockSchedulerDisplayPreferencesRepository); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(true); + + _sut = new GetSchedulerDisplayPreferencesQueryHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork); + } + + [Fact] + public async Task HandleAsync_WhenDisplayPreferencesExist_ShouldReturnThemAsResponse() + { + // Arrange + SchedulerDisplayPreferencesEntity displayPreferences = _schedulerDisplayPreferencesEntityFixture.Create( + userId: _userId, + jobTypeFilter: ScheduledTaskType.ScanMediaLibraries, + displayTimeSpan: 60, + displayTimeUnit: SchedulerDisplayTimeUnit.Hours); + _mockSchedulerDisplayPreferencesRepository.GetByUserIdAsync(_userId, Arg.Any()) + .Returns(Result.From(displayPreferences)); + + // Act + Result result = await _sut.HandleAsync(new GetSchedulerDisplayPreferencesQuery(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(_userId, result.Value.UserId); + Assert.Equal(ScheduledTaskType.ScanMediaLibraries, result.Value.JobTypeFilter); + Assert.Equal(60, result.Value.DisplayTimeSpan); + Assert.Equal(SchedulerDisplayTimeUnit.Hours, result.Value.DisplayTimeUnit); + } + + [Fact] + public async Task HandleAsync_WhenNoDisplayPreferencesExist_ShouldReturnDefaultResponse() + { + // Arrange + _mockSchedulerDisplayPreferencesRepository.GetByUserIdAsync(_userId, Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(new GetSchedulerDisplayPreferencesQuery(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(_userId, result.Value.UserId); + Assert.Null(result.Value.JobTypeFilter); + Assert.Equal(DEFAULT_DISPLAY_TIME_SPAN, result.Value.DisplayTimeSpan); + Assert.Equal(DEFAULT_DISPLAY_TIME_UNIT, result.Value.DisplayTimeUnit); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized() + { + // Arrange + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(new GetSchedulerDisplayPreferencesQuery(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockSchedulerDisplayPreferencesRepository.DidNotReceive().GetByUserIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized() + { + // Arrange + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); + + // Act + Result result = await _sut.HandleAsync(new GetSchedulerDisplayPreferencesQuery(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockSchedulerDisplayPreferencesRepository.DidNotReceive().GetByUserIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetByUserIdReturnsError_ShouldReturnError() + { + // Arrange + Error error = Error.Failure("Database.Error", "Failed to get the display preferences"); + _mockSchedulerDisplayPreferencesRepository.GetByUserIdAsync(_userId, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(new GetSchedulerDisplayPreferencesQuery(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Scheduling/ScheduledJobExecutionRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Scheduling/ScheduledJobExecutionRepositoryTests.cs new file mode 100644 index 00000000..36295884 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Scheduling/ScheduledJobExecutionRepositoryTests.cs @@ -0,0 +1,237 @@ +#region ========================================================================= USING ===================================================================================== +using EntityFrameworkCore.Testing.NSubstitute; +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.DataAccess.Core.Repositories.Scheduling; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.UnitTests.Core.Repositories.Scheduling; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobExecutionRepositoryTests +{ + private readonly LuminaDbContext _mockContext; + private readonly ScheduledJobExecutionRepository _sut; + private readonly ScheduledJobExecutionEntityFixture _scheduledJobExecutionEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ScheduledJobExecutionRepositoryTests() + { + _mockContext = Create.MockedDbContextFor(); + _sut = new ScheduledJobExecutionRepository(_mockContext); + } + + [Fact] + public async Task GetByIdAsync_WhenExecutionExists_ShouldReturnExecution() + { + // Arrange + ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create(); + _mockContext.ScheduledJobExecutions.Add(execution); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByIdAsync(execution.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(execution.Id, result.Value!.Id); + Assert.Equal(execution.ScheduledJobId, result.Value.ScheduledJobId); + } + + [Fact] + public async Task GetByIdAsync_WhenExecutionDoesNotExist_ShouldReturnNull() + { + // Act + Result result = await _sut.GetByIdAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task InsertAsync_WhenExecutionDoesNotExist_ShouldAddExecutionToContextAndReturnCreated() + { + // Arrange + ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create(); + + // Act + Result result = await _sut.InsertAsync(execution, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + EntityEntry? addedExecution = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == execution.Id); + Assert.NotNull(addedExecution); + } + + [Fact] + public async Task InsertAsync_WhenExecutionAlreadyExists_ShouldReturnError() + { + // Arrange + ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create(); + _mockContext.ScheduledJobExecutions.Add(execution); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.InsertAsync(execution, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Scheduling.ScheduledJobExecutionAlreadyExists, result.FirstError); + } + + [Fact] + public async Task UpdateAsync_WhenExecutionExists_ShouldUpdateItsPropertiesAndReturnUpdated() + { + // Arrange + DateTime completedOnUtc = DateTime.UtcNow; + ScheduledJobExecutionEntity existingExecution = _scheduledJobExecutionEntityFixture.Create(completedOnUtc: null); + _mockContext.ScheduledJobExecutions.Add(existingExecution); + await _mockContext.SaveChangesAsync(); + + ScheduledJobExecutionEntity updatedExecution = _scheduledJobExecutionEntityFixture.Create( + id: existingExecution.Id, + scheduledJobId: existingExecution.ScheduledJobId, + isCycleRun: existingExecution.IsCycleRun, + startedOnUtc: existingExecution.StartedOnUtc, + completedOnUtc: completedOnUtc); + + // Act + Result result = await _sut.UpdateAsync(updatedExecution, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + ScheduledJobExecutionEntity? modifiedExecution = await _mockContext.ScheduledJobExecutions.FirstOrDefaultAsync(execution => execution.Id == existingExecution.Id); + Assert.NotNull(modifiedExecution); + Assert.Equal(completedOnUtc, modifiedExecution!.CompletedOnUtc); + } + + [Fact] + public async Task UpdateAsync_WhenExecutionDoesNotExist_ShouldReturnError() + { + // Arrange + ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create(); + + // Act + Result result = await _sut.UpdateAsync(execution, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Scheduling.ScheduledJobExecutionNotFound, result.FirstError); + } + + [Fact] + public async Task GetOpenByScheduledJobIdAsync_WhenAnOpenExecutionExists_ShouldReturnTheMostRecentOne() + { + // Arrange + Guid scheduledJobId = Guid.NewGuid(); + DateTime mostRecentStart = DateTime.UtcNow.AddMinutes(-1); + ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: scheduledJobId, startedOnUtc: mostRecentStart, completedOnUtc: null); + ScheduledJobExecutionEntity olderOpenExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: scheduledJobId, startedOnUtc: mostRecentStart.AddMinutes(-10), completedOnUtc: null); + ScheduledJobExecutionEntity closedExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: scheduledJobId, startedOnUtc: mostRecentStart.AddMinutes(-5), completedOnUtc: DateTime.UtcNow); + _mockContext.ScheduledJobExecutions.AddRange(openExecution, olderOpenExecution, closedExecution); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetOpenByScheduledJobIdAsync(scheduledJobId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(openExecution.Id, result.Value!.Id); + } + + [Fact] + public async Task GetOpenByScheduledJobIdAsync_WhenNoOpenExecutionExists_ShouldReturnNull() + { + // Arrange + Guid scheduledJobId = Guid.NewGuid(); + ScheduledJobExecutionEntity closedExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: scheduledJobId, completedOnUtc: DateTime.UtcNow); + _mockContext.ScheduledJobExecutions.Add(closedExecution); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetOpenByScheduledJobIdAsync(scheduledJobId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetByTimeRangeAsync_WhenExecutionsStartedInTheRange_ShouldReturnThemOrderedByStartTime() + { + // Arrange + DateTime fromUtc = DateTime.UtcNow.AddHours(-2); + DateTime toUtc = DateTime.UtcNow; + ScheduledJobExecutionEntity inRange1 = _scheduledJobExecutionEntityFixture.Create(startedOnUtc: fromUtc.AddMinutes(1)); + ScheduledJobExecutionEntity inRange2 = _scheduledJobExecutionEntityFixture.Create(startedOnUtc: fromUtc.AddMinutes(30)); + ScheduledJobExecutionEntity beforeRange = _scheduledJobExecutionEntityFixture.Create(startedOnUtc: fromUtc.AddMinutes(-10)); + ScheduledJobExecutionEntity afterRange = _scheduledJobExecutionEntityFixture.Create(startedOnUtc: toUtc.AddMinutes(10)); + _mockContext.ScheduledJobExecutions.AddRange(inRange1, inRange2, beforeRange, afterRange); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetByTimeRangeAsync(fromUtc, toUtc, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + List executions = [.. result.Value]; + Assert.Equal(2, executions.Count); + Assert.Equal(inRange1.Id, executions[0].Id); + Assert.Equal(inRange2.Id, executions[1].Id); + } + + [Fact] + public async Task DeleteByScheduledJobIdAsync_WhenExecutionsExist_ShouldRemoveThemAllAndReturnSuccess() + { + // Arrange + Guid scheduledJobId = Guid.NewGuid(); + ScheduledJobExecutionEntity execution1 = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: scheduledJobId); + ScheduledJobExecutionEntity execution2 = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: scheduledJobId); + ScheduledJobExecutionEntity otherExecution = _scheduledJobExecutionEntityFixture.Create(); + _mockContext.ScheduledJobExecutions.AddRange(execution1, execution2, otherExecution); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.DeleteByScheduledJobIdAsync(scheduledJobId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Success, result.Value); + Assert.Equal(2, _mockContext.ChangeTracker.Entries().Count(entry => entry.State == EntityState.Deleted)); + Assert.Contains(_mockContext.ChangeTracker.Entries(), entry => entry.State == EntityState.Deleted && entry.Entity.Id == execution1.Id); + Assert.Contains(_mockContext.ChangeTracker.Entries(), entry => entry.State == EntityState.Deleted && entry.Entity.Id == execution2.Id); + } + + [Fact] + public async Task DeleteByScheduledJobIdAsync_WhenNoExecutionsExist_ShouldReturnSuccess() + { + // Act + Result result = await _sut.DeleteByScheduledJobIdAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Success, result.Value); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Scheduling/ScheduledJobRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Scheduling/ScheduledJobRepositoryTests.cs new file mode 100644 index 00000000..b45c6ff8 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Scheduling/ScheduledJobRepositoryTests.cs @@ -0,0 +1,240 @@ +#region ========================================================================= USING ===================================================================================== +using EntityFrameworkCore.Testing.NSubstitute; +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.DataAccess.Core.Repositories.Scheduling; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.UnitTests.Core.Repositories.Scheduling; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobRepositoryTests +{ + private readonly LuminaDbContext _mockContext; + private readonly ScheduledJobRepository _sut; + private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ScheduledJobRepositoryTests() + { + _mockContext = Create.MockedDbContextFor(); + _sut = new ScheduledJobRepository(_mockContext); + } + + [Fact] + public async Task GetByIdAsync_WhenScheduledJobExists_ShouldReturnScheduledJob() + { + // Arrange + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(); + _mockContext.ScheduledJobs.Add(scheduledJob); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByIdAsync(scheduledJob.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(scheduledJob.Id, result.Value!.Id); + Assert.Equal(scheduledJob.Name, result.Value.Name); + } + + [Fact] + public async Task GetByIdAsync_WhenScheduledJobDoesNotExist_ShouldReturnNull() + { + // Act + Result result = await _sut.GetByIdAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetByIdWithoutTrackingAsync_WhenScheduledJobExists_ShouldReturnScheduledJob() + { + // Arrange + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(); + _mockContext.ScheduledJobs.Add(scheduledJob); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByIdWithoutTrackingAsync(scheduledJob.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(scheduledJob.Id, result.Value!.Id); + Assert.Equal(scheduledJob.Name, result.Value.Name); + } + + [Fact] + public async Task GetByIdWithoutTrackingAsync_WhenScheduledJobDoesNotExist_ShouldReturnNull() + { + // Act + Result result = await _sut.GetByIdWithoutTrackingAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetAllAsync_WhenScheduledJobsExist_ShouldReturnAllScheduledJobs() + { + // Arrange + ScheduledJobEntity scheduledJob1 = _scheduledJobEntityFixture.Create(); + ScheduledJobEntity scheduledJob2 = _scheduledJobEntityFixture.Create(); + _mockContext.ScheduledJobs.AddRange(scheduledJob1, scheduledJob2); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetAllAsync(CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Count()); + } + + [Fact] + public async Task GetActiveOrRunningAsync_WhenScheduledJobsAreActiveOrRunning_ShouldReturnOnlyThem() + { + // Arrange + ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active); + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running); + ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added); + ScheduledJobEntity completedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Completed); + _mockContext.ScheduledJobs.AddRange(activeJob, runningJob, addedJob, completedJob); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetActiveOrRunningAsync(CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + List scheduledJobs = result.Value.ToList(); + Assert.Equal(2, scheduledJobs.Count); + Assert.Contains(scheduledJobs, scheduledJob => scheduledJob.Id == activeJob.Id); + Assert.Contains(scheduledJobs, scheduledJob => scheduledJob.Id == runningJob.Id); + } + + [Fact] + public async Task InsertAsync_WhenScheduledJobDoesNotExist_ShouldAddScheduledJobToContextAndReturnCreated() + { + // Arrange + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(); + + // Act + Result result = await _sut.InsertAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + EntityEntry? addedScheduledJob = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == scheduledJob.Id); + Assert.NotNull(addedScheduledJob); + Assert.Equal(scheduledJob.Name, addedScheduledJob!.Entity.Name); + } + + [Fact] + public async Task InsertAsync_WhenScheduledJobAlreadyExists_ShouldReturnError() + { + // Arrange + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(); + _mockContext.ScheduledJobs.Add(scheduledJob); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.InsertAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Scheduling.ScheduledJobAlreadyExists, result.FirstError); + } + + [Fact] + public async Task UpdateAsync_WhenScheduledJobExists_ShouldUpdateItsPropertiesAndReturnUpdated() + { + // Arrange + ScheduledJobEntity existingScheduledJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added); + _mockContext.ScheduledJobs.Add(existingScheduledJob); + await _mockContext.SaveChangesAsync(); + + ScheduledJobEntity updatedScheduledJob = _scheduledJobEntityFixture.Create( + id: existingScheduledJob.Id, + name: "Updated name", + status: ScheduledJobStatus.Active); + + // Act + Result result = await _sut.UpdateAsync(updatedScheduledJob, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + ScheduledJobEntity? modifiedScheduledJob = await _mockContext.ScheduledJobs.FirstOrDefaultAsync(scheduledJob => scheduledJob.Id == existingScheduledJob.Id); + Assert.NotNull(modifiedScheduledJob); + Assert.Equal("Updated name", modifiedScheduledJob!.Name); + Assert.Equal(ScheduledJobStatus.Active, modifiedScheduledJob.Status); + } + + [Fact] + public async Task UpdateAsync_WhenScheduledJobDoesNotExist_ShouldReturnError() + { + // Arrange + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(); + + // Act + Result result = await _sut.UpdateAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Scheduling.ScheduledJobNotFound, result.FirstError); + } + + [Fact] + public async Task DeleteByIdAsync_WhenScheduledJobExists_ShouldRemoveItAndReturnDeleted() + { + // Arrange + ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(); + _mockContext.ScheduledJobs.Add(scheduledJob); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.DeleteByIdAsync(scheduledJob.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Deleted, result.Value); + EntityEntry? deletedScheduledJob = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entry => entry.State == EntityState.Deleted && entry.Entity.Id == scheduledJob.Id); + Assert.NotNull(deletedScheduledJob); + } + + [Fact] + public async Task DeleteByIdAsync_WhenScheduledJobDoesNotExist_ShouldReturnError() + { + // Act + Result result = await _sut.DeleteByIdAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Scheduling.ScheduledJobNotFound, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Scheduling/SchedulerDisplayPreferencesRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Scheduling/SchedulerDisplayPreferencesRepositoryTests.cs new file mode 100644 index 00000000..fe942ff6 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Scheduling/SchedulerDisplayPreferencesRepositoryTests.cs @@ -0,0 +1,123 @@ +#region ========================================================================= USING ===================================================================================== +using EntityFrameworkCore.Testing.NSubstitute; +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.DataAccess.Core.Repositories.Scheduling; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.UnitTests.Core.Repositories.Scheduling; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SchedulerDisplayPreferencesRepositoryTests +{ + private readonly LuminaDbContext _mockContext; + private readonly SchedulerDisplayPreferencesRepository _sut; + private readonly SchedulerDisplayPreferencesEntityFixture _schedulerDisplayPreferencesEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public SchedulerDisplayPreferencesRepositoryTests() + { + _mockContext = Create.MockedDbContextFor(); + _sut = new SchedulerDisplayPreferencesRepository(_mockContext); + } + + [Fact] + public async Task GetByUserIdAsync_WhenDisplayPreferencesExist_ShouldReturnThem() + { + // Arrange + SchedulerDisplayPreferencesEntity displayPreferences = _schedulerDisplayPreferencesEntityFixture.Create(); + _mockContext.SchedulerDisplayPreferences.Add(displayPreferences); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByUserIdAsync(displayPreferences.UserId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(displayPreferences.Id, result.Value!.Id); + Assert.Equal(displayPreferences.UserId, result.Value.UserId); + Assert.Equal(displayPreferences.DisplayTimeSpan, result.Value.DisplayTimeSpan); + } + + [Fact] + public async Task GetByUserIdAsync_WhenDisplayPreferencesDoNotExist_ShouldReturnNull() + { + // Act + Result result = await _sut.GetByUserIdAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task UpsertAsync_WhenDisplayPreferencesDoNotExist_ShouldAddThemToContextAndReturnUpdated() + { + // Arrange + SchedulerDisplayPreferencesEntity displayPreferences = _schedulerDisplayPreferencesEntityFixture.Create( + displayTimeSpan: 30, + displayTimeUnit: SchedulerDisplayTimeUnit.Minutes); + + // Act + Result result = await _sut.UpsertAsync(displayPreferences, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + EntityEntry? addedPreferences = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.UserId == displayPreferences.UserId); + Assert.NotNull(addedPreferences); + } + + [Fact] + public async Task UpsertAsync_WhenDisplayPreferencesAlreadyExist_ShouldUpdateTheMutableFieldsAndReturnUpdated() + { + // Arrange + Guid userId = Guid.NewGuid(); + SchedulerDisplayPreferencesEntity existingPreferences = _schedulerDisplayPreferencesEntityFixture.Create( + userId: userId, + jobTypeFilter: ScheduledTaskType.ScanMediaLibraries, + displayTimeSpan: 10, + displayTimeUnit: SchedulerDisplayTimeUnit.Hours); + _mockContext.SchedulerDisplayPreferences.Add(existingPreferences); + await _mockContext.SaveChangesAsync(); + + SchedulerDisplayPreferencesEntity updatedPreferences = _schedulerDisplayPreferencesEntityFixture.Create( + userId: userId, + jobTypeFilter: ScheduledTaskType.CleanTemporaryFiles, + displayTimeSpan: 60, + displayTimeUnit: SchedulerDisplayTimeUnit.Days); + + // Act + Result result = await _sut.UpsertAsync(updatedPreferences, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + SchedulerDisplayPreferencesEntity? modifiedPreferences = await _mockContext.SchedulerDisplayPreferences + .FirstOrDefaultAsync(preferences => preferences.UserId == userId); + Assert.NotNull(modifiedPreferences); + // The Id and the ownership of the existing preferences are preserved. + Assert.Equal(existingPreferences.Id, modifiedPreferences!.Id); + Assert.Equal(ScheduledTaskType.CleanTemporaryFiles, modifiedPreferences.JobTypeFilter); + Assert.Equal(60, modifiedPreferences.DisplayTimeSpan); + Assert.Equal(SchedulerDisplayTimeUnit.Days, modifiedPreferences.DisplayTimeUnit); + Assert.Single(_mockContext.ChangeTracker.Entries()); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs index a9349aa8..3ff2ee59 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs @@ -1,20 +1,25 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Authorization; +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.DataAccess.Core.Seed; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; using NSubstitute; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -543,4 +548,58 @@ public class DataSeedServiceTests await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } + + [Fact] + public async Task SetDefaultScheduledJobsAsync_WhenCalled_ShouldInsertTheFiveDefaultJobsAndReturnCreated() + { + // Arrange + Guid adminUserId = Guid.NewGuid(); + IScheduledJobRepository mockScheduledJobRepository = Substitute.For(); + _mockUnitOfWork.ScheduledJobRepository.Returns(mockScheduledJobRepository); + List capturedScheduledJobs = []; + mockScheduledJobRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created) + .AndDoes(info => capturedScheduledJobs.Add(info.Arg())); + + // Act + Result result = await _sut.SetDefaultScheduledJobsAsync(adminUserId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + Assert.Equal(5, capturedScheduledJobs.Count); + Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(ScheduledJobStatus.Active, scheduledJob.Status)); + Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(adminUserId, scheduledJob.OwnerUserId)); + Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(adminUserId, scheduledJob.CreatedBy)); + Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(_fixedUtcNow, scheduledJob.CreatedOnUtc)); + Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.ScanMediaLibraries && scheduledJob.ScheduleType == ScheduleType.DailyAtHourAndMinute && scheduledJob.Hour == 0 && scheduledJob.Minute == 0); + Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.CleanTemporaryFiles && scheduledJob.ScheduleType == ScheduleType.OnceAtStartup); + Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.CleanTemporaryFiles && scheduledJob.ScheduleType == ScheduleType.WithIntervalInMinutes && scheduledJob.IntervalMinutes == 720); + Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.RepairThemes && scheduledJob.ScheduleType == ScheduleType.OnceAtStartup); + Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.CleanScheduledJobExecutionHistory && scheduledJob.ScheduleType == ScheduleType.OnceAtStartup); + + await mockScheduledJobRepository.Received(5).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await mockScheduledJobRepository.DidNotReceive().GetAllAsync(Arg.Any()); + } + + [Fact] + public async Task SetDefaultScheduledJobsAsync_WhenInsertScheduledJobFails_ShouldReturnError() + { + // Arrange + Guid adminUserId = Guid.NewGuid(); + IScheduledJobRepository mockScheduledJobRepository = Substitute.For(); + _mockUnitOfWork.ScheduledJobRepository.Returns(mockScheduledJobRepository); + Error expectedError = Error.Failure("ScheduledJobs.InsertFailed", "Failed to insert the scheduled job"); + mockScheduledJobRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created, expectedError); + + // Act + Result result = await _sut.SetDefaultScheduledJobsAsync(adminUserId, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(expectedError, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibraryDeletedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibraryDeletedDomainEventTests.cs index 5fc22425..5b145a8e 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibraryDeletedDomainEventTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibraryDeletedDomainEventTests.cs @@ -3,6 +3,7 @@ using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -16,6 +17,7 @@ namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedC public class LibraryDeletedDomainEventTests { private readonly LibraryFixture _libraryFixture = new(); + private readonly LibraryDeletedDomainEventFixture _libraryDeletedDomainEventFixture = new(); [Fact] public void Constructor_WhenCalled_ShouldSetAllProperties() @@ -26,7 +28,7 @@ public class LibraryDeletedDomainEventTests DateTime occurredOnUtc = DateTime.UtcNow; // Act - LibraryDeletedDomainEvent domainEvent = new(id, library, occurredOnUtc); + LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(id, library, occurredOnUtc); // Assert Assert.Equal(id, domainEvent.Id); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibrarySavedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibrarySavedDomainEventTests.cs index b00d2f18..c87ef166 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibrarySavedDomainEventTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibrarySavedDomainEventTests.cs @@ -3,6 +3,7 @@ using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -16,6 +17,7 @@ namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedC public class LibrarySavedDomainEventTests { private readonly LibraryFixture _libraryFixture = new(); + private readonly LibrarySavedDomainEventFixture _librarySavedDomainEventFixture = new(); [Fact] public void Constructor_WhenCalled_ShouldSetAllProperties() @@ -26,7 +28,7 @@ public class LibrarySavedDomainEventTests DateTime occurredOnUtc = DateTime.UtcNow; // Act - LibrarySavedDomainEvent domainEvent = new(id, library, occurredOnUtc); + LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(id, library, occurredOnUtc); // Assert Assert.Equal(id, domainEvent.Id); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryMediaItemDeletedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryMediaItemDeletedDomainEventTests.cs index ba23dd34..86fe538e 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryMediaItemDeletedDomainEventTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryMediaItemDeletedDomainEventTests.cs @@ -4,6 +4,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using System; using System.Diagnostics.CodeAnalysis; @@ -19,6 +20,7 @@ public class LibraryMediaItemDeletedDomainEventTests { private readonly LibraryIdFixture _libraryIdFixture = new(); private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new(); + private readonly LibraryMediaItemDeletedDomainEventFixture _libraryMediaItemDeletedDomainEventFixture = new(); [Fact] public void Constructor_WhenCalled_ShouldSetAllProperties() @@ -31,7 +33,7 @@ public class LibraryMediaItemDeletedDomainEventTests DateTime occurredOnUtc = DateTime.UtcNow; // Act - LibraryMediaItemDeletedDomainEvent domainEvent = new(id, libraryId, compositeId, path, occurredOnUtc); + LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(id, libraryId, compositeId, path, occurredOnUtc); // Assert Assert.Equal(id, domainEvent.Id); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanCancelledDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanCancelledDomainEventTests.cs index 27b2b775..55292a22 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanCancelledDomainEventTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanCancelledDomainEventTests.cs @@ -4,6 +4,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using System; using System.Diagnostics.CodeAnalysis; @@ -19,6 +20,7 @@ public class LibraryScanCancelledDomainEventTests { private readonly ScanIdFixture _scanIdFixture = new(); private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly LibraryScanCancelledDomainEventFixture _libraryScanCancelledDomainEventFixture = new(); [Fact] public void Constructor_WhenCalled_ShouldSetAllProperties() @@ -30,7 +32,7 @@ public class LibraryScanCancelledDomainEventTests DateTime occurredOnUtc = DateTime.UtcNow; // Act - LibraryScanCancelledDomainEvent domainEvent = new(id, scanId, libraryId, occurredOnUtc); + LibraryScanCancelledDomainEvent domainEvent = _libraryScanCancelledDomainEventFixture.Create(id, scanId, libraryId, occurredOnUtc); // Assert Assert.Equal(id, domainEvent.Id); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEventTests.cs index 8929c22f..1373e818 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEventTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEventTests.cs @@ -4,6 +4,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using System; using System.Diagnostics.CodeAnalysis; @@ -19,6 +20,7 @@ public class LibraryScanFailedDomainEventTests { private readonly LibraryIdFixture _libraryIdFixture = new(); private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new(); + private readonly LibraryScanFailedDomainEventFixture _libraryScanFailedDomainEventFixture = new(); [Fact] public void Constructor_WhenCalledWithErrorMessage_ShouldSetAllProperties() @@ -31,7 +33,12 @@ public class LibraryScanFailedDomainEventTests string errorMessage = "Scan failed unexpectedly."; // Act - LibraryScanFailedDomainEvent domainEvent = new(id, libraryId, compositeId, occurredOnUtc, errorMessage); + LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create( + id: id, + libraryId: libraryId, + mediaLibraryScanCompositeId: compositeId, + occurredOnUtc: occurredOnUtc, + errorMessage: errorMessage); // Assert Assert.Equal(id, domainEvent.Id); @@ -46,11 +53,7 @@ public class LibraryScanFailedDomainEventTests public void Constructor_WhenCalledWithoutErrorMessage_ShouldDefaultErrorMessageToNull() { // Act - LibraryScanFailedDomainEvent domainEvent = new( - Guid.NewGuid(), - _libraryIdFixture.Create(), - _mediaLibraryScanCompositeIdFixture.Create(), - DateTime.UtcNow); + LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create(includeErrorMessage: false); // Assert Assert.Null(domainEvent.ErrorMessage); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFinishedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFinishedDomainEventTests.cs index c411a16e..bfeb3fd0 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFinishedDomainEventTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFinishedDomainEventTests.cs @@ -2,6 +2,7 @@ using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using System; using System.Diagnostics.CodeAnalysis; @@ -16,6 +17,7 @@ namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedC public class LibraryScanFinishedDomainEventTests { private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new(); + private readonly LibraryScanFinishedDomainEventFixture _libraryScanFinishedDomainEventFixture = new(); [Fact] public void Constructor_WhenCalled_ShouldSetAllProperties() @@ -26,7 +28,7 @@ public class LibraryScanFinishedDomainEventTests DateTime occurredOnUtc = DateTime.UtcNow; // Act - LibraryScanFinishedDomainEvent domainEvent = new(id, compositeId, occurredOnUtc); + LibraryScanFinishedDomainEvent domainEvent = _libraryScanFinishedDomainEventFixture.Create(id, compositeId, occurredOnUtc); // Assert Assert.Equal(id, domainEvent.Id); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanJobProgressChangedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanJobProgressChangedDomainEventTests.cs index f22f9345..5585c175 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanJobProgressChangedDomainEventTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanJobProgressChangedDomainEventTests.cs @@ -4,6 +4,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using System; using System.Diagnostics.CodeAnalysis; @@ -20,6 +21,7 @@ public class LibraryScanJobProgressChangedDomainEventTests private readonly LibraryIdFixture _libraryIdFixture = new(); private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new(); private readonly MediaLibraryScanJobProgressFixture _mediaLibraryScanJobProgressFixture = new(); + private readonly LibraryScanJobProgressChangedDomainEventFixture _libraryScanJobProgressChangedDomainEventFixture = new(); [Fact] public void Constructor_WhenCalled_ShouldSetAllProperties() @@ -32,7 +34,7 @@ public class LibraryScanJobProgressChangedDomainEventTests DateTime occurredOnUtc = DateTime.UtcNow; // Act - LibraryScanJobProgressChangedDomainEvent domainEvent = new(id, libraryId, compositeId, progress, occurredOnUtc); + LibraryScanJobProgressChangedDomainEvent domainEvent = _libraryScanJobProgressChangedDomainEventFixture.Create(id, libraryId, compositeId, progress, occurredOnUtc); // Assert Assert.Equal(id, domainEvent.Id); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanProgressChangedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanProgressChangedDomainEventTests.cs index a96bac75..a62d3ecc 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanProgressChangedDomainEventTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanProgressChangedDomainEventTests.cs @@ -4,6 +4,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using System; using System.Diagnostics.CodeAnalysis; @@ -19,6 +20,7 @@ public class LibraryScanProgressChangedDomainEventTests { private readonly LibraryIdFixture _libraryIdFixture = new(); private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new(); + private readonly LibraryScanProgressChangedDomainEventFixture _libraryScanProgressChangedDomainEventFixture = new(); [Fact] public void Constructor_WhenCalled_ShouldSetAllProperties() @@ -30,7 +32,7 @@ public class LibraryScanProgressChangedDomainEventTests DateTime occurredOnUtc = DateTime.UtcNow; // Act - LibraryScanProgressChangedDomainEvent domainEvent = new(id, libraryId, compositeId, occurredOnUtc); + LibraryScanProgressChangedDomainEvent domainEvent = _libraryScanProgressChangedDomainEventFixture.Create(id, libraryId, compositeId, occurredOnUtc); // Assert Assert.Equal(id, domainEvent.Id); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanQueuedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanQueuedDomainEventTests.cs index f45f64a5..14029bae 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanQueuedDomainEventTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanQueuedDomainEventTests.cs @@ -4,6 +4,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using System; using System.Diagnostics.CodeAnalysis; @@ -19,6 +20,7 @@ public class LibraryScanQueuedDomainEventTests { private readonly ScanIdFixture _scanIdFixture = new(); private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly LibraryScanQueuedDomainEventFixture _libraryScanQueuedDomainEventFixture = new(); [Fact] public void Constructor_WhenCalled_ShouldSetAllProperties() @@ -30,7 +32,7 @@ public class LibraryScanQueuedDomainEventTests DateTime occurredOnUtc = DateTime.UtcNow; // Act - LibraryScanQueuedDomainEvent domainEvent = new(id, scanId, libraryId, occurredOnUtc); + LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create(id, scanId, libraryId, occurredOnUtc); // Assert Assert.Equal(id, domainEvent.Id); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanStartedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanStartedDomainEventTests.cs index e532b0ed..fd54bb86 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanStartedDomainEventTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanStartedDomainEventTests.cs @@ -3,6 +3,7 @@ using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -16,6 +17,7 @@ namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedC public class LibraryScanStartedDomainEventTests { private readonly LibraryScanFixture _libraryScanFixture = new(); + private readonly LibraryScanStartedDomainEventFixture _libraryScanStartedDomainEventFixture = new(); [Fact] public void Constructor_WhenCalled_ShouldSetAllProperties() @@ -26,7 +28,7 @@ public class LibraryScanStartedDomainEventTests DateTime occurredOnUtc = DateTime.UtcNow; // Act - LibraryScanStartedDomainEvent domainEvent = new(id, scan, occurredOnUtc); + LibraryScanStartedDomainEvent domainEvent = _libraryScanStartedDomainEventFixture.Create(id, scan, occurredOnUtc); // Assert Assert.Equal(id, domainEvent.Id); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserIdTests.cs new file mode 100644 index 00000000..8529b2a3 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserIdTests.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UserIdTests +{ + private readonly UserIdFixture _userIdFixture = new(); + + [Fact] + public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue() + { + // Act + UserId userId = UserId.CreateUnique(); + + // Assert + Assert.NotNull(userId); + Assert.NotEqual(default, userId.Value); + } + + [Fact] + public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue() + { + // Arrange + Guid value = Guid.NewGuid(); + + // Act + UserId userId = UserId.Create(value); + + // Assert + Assert.Equal(value, userId.Value); + } + + [Fact] + public void Equals_WithSameValue_ShouldReturnTrue() + { + // Arrange + Guid value = Guid.NewGuid(); + UserId firstId = _userIdFixture.Create(value); + UserId secondId = _userIdFixture.Create(value); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + UserId firstId = _userIdFixture.Create(); + UserId secondId = _userIdFixture.Create(); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobAddedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobAddedDomainEventTests.cs new file mode 100644 index 00000000..a6562252 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobAddedDomainEventTests.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobAddedDomainEventTests +{ + private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new(); + private readonly ScheduledJobAddedDomainEventFixture _scheduledJobAddedDomainEventFixture = new(); + + [Fact] + public void Constructor_WhenCalled_ShouldSetAllProperties() + { + // Arrange + Guid id = Guid.NewGuid(); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + DateTime occurredOnUtc = DateTime.UtcNow; + + // Act + ScheduledJobAddedDomainEvent domainEvent = _scheduledJobAddedDomainEventFixture.Create(id, scheduledJobId, occurredOnUtc); + + // Assert + Assert.Equal(id, domainEvent.Id); + Assert.Equal(scheduledJobId, domainEvent.ScheduledJobId); + Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc); + Assert.IsType(domainEvent, exactMatch: false); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobCycleStartedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobCycleStartedDomainEventTests.cs new file mode 100644 index 00000000..17d93db2 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobCycleStartedDomainEventTests.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobCycleStartedDomainEventTests +{ + private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new(); + private readonly ScheduledJobCycleStartedDomainEventFixture _scheduledJobCycleStartedDomainEventFixture = new(); + + [Fact] + public void Constructor_WhenCalled_ShouldSetAllProperties() + { + // Arrange + Guid id = Guid.NewGuid(); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + DateTime occurredOnUtc = DateTime.UtcNow; + + // Act + ScheduledJobCycleStartedDomainEvent domainEvent = _scheduledJobCycleStartedDomainEventFixture.Create(id, scheduledJobId, occurredOnUtc); + + // Assert + Assert.Equal(id, domainEvent.Id); + Assert.Equal(scheduledJobId, domainEvent.ScheduledJobId); + Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc); + Assert.IsType(domainEvent, exactMatch: false); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobCycleStoppedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobCycleStoppedDomainEventTests.cs new file mode 100644 index 00000000..fc727bbb --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobCycleStoppedDomainEventTests.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobCycleStoppedDomainEventTests +{ + private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new(); + private readonly ScheduledJobCycleStoppedDomainEventFixture _scheduledJobCycleStoppedDomainEventFixture = new(); + + [Fact] + public void Constructor_WhenCalled_ShouldSetAllProperties() + { + // Arrange + Guid id = Guid.NewGuid(); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + DateTime occurredOnUtc = DateTime.UtcNow; + + // Act + ScheduledJobCycleStoppedDomainEvent domainEvent = _scheduledJobCycleStoppedDomainEventFixture.Create(id, scheduledJobId, occurredOnUtc); + + // Assert + Assert.Equal(id, domainEvent.Id); + Assert.Equal(scheduledJobId, domainEvent.ScheduledJobId); + Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc); + Assert.IsType(domainEvent, exactMatch: false); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobExecutionCompletedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobExecutionCompletedDomainEventTests.cs new file mode 100644 index 00000000..8c8bdaa5 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobExecutionCompletedDomainEventTests.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobExecutionCompletedDomainEventTests +{ + private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new(); + private readonly ScheduledJobExecutionCompletedDomainEventFixture _scheduledJobExecutionCompletedDomainEventFixture = new(); + + [Fact] + public void Constructor_WhenCalled_ShouldSetAllProperties() + { + // Arrange + Guid id = Guid.NewGuid(); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + Guid runId = Guid.NewGuid(); + ScheduledTaskType taskType = ScheduledTaskType.CleanTemporaryFiles; + bool isCycleRun = false; + DateTime completedOnUtc = DateTime.UtcNow; + + // Act + ScheduledJobExecutionCompletedDomainEvent domainEvent = _scheduledJobExecutionCompletedDomainEventFixture.Create(id, scheduledJobId, runId, taskType, isCycleRun, completedOnUtc); + + // Assert + Assert.Equal(id, domainEvent.Id); + Assert.Equal(scheduledJobId, domainEvent.ScheduledJobId); + Assert.Equal(runId, domainEvent.RunId); + Assert.Equal(taskType, domainEvent.TaskType); + Assert.Equal(isCycleRun, domainEvent.IsCycleRun); + Assert.Equal(completedOnUtc, domainEvent.CompletedOnUtc); + Assert.Equal(completedOnUtc, domainEvent.OccurredOnUtc); + Assert.IsType(domainEvent, exactMatch: false); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobExecutionStartedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobExecutionStartedDomainEventTests.cs new file mode 100644 index 00000000..f3843323 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobExecutionStartedDomainEventTests.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobExecutionStartedDomainEventTests +{ + private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new(); + private readonly ScheduledJobExecutionStartedDomainEventFixture _scheduledJobExecutionStartedDomainEventFixture = new(); + + [Fact] + public void Constructor_WhenCalled_ShouldSetAllProperties() + { + // Arrange + Guid id = Guid.NewGuid(); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + Guid runId = Guid.NewGuid(); + ScheduledTaskType taskType = ScheduledTaskType.ScanMediaLibraries; + bool isCycleRun = true; + DateTime startedOnUtc = DateTime.UtcNow; + + // Act + ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create(id, scheduledJobId, runId, taskType, isCycleRun, startedOnUtc); + + // Assert + Assert.Equal(id, domainEvent.Id); + Assert.Equal(scheduledJobId, domainEvent.ScheduledJobId); + Assert.Equal(runId, domainEvent.RunId); + Assert.Equal(taskType, domainEvent.TaskType); + Assert.Equal(isCycleRun, domainEvent.IsCycleRun); + Assert.Equal(startedOnUtc, domainEvent.StartedOnUtc); + Assert.Equal(startedOnUtc, domainEvent.OccurredOnUtc); + Assert.IsType(domainEvent, exactMatch: false); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobExecutionStoppedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobExecutionStoppedDomainEventTests.cs new file mode 100644 index 00000000..fbcee106 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobExecutionStoppedDomainEventTests.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobExecutionStoppedDomainEventTests +{ + private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new(); + private readonly ScheduledJobExecutionStoppedDomainEventFixture _scheduledJobExecutionStoppedDomainEventFixture = new(); + + [Fact] + public void Constructor_WhenCalled_ShouldSetAllProperties() + { + // Arrange + Guid id = Guid.NewGuid(); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + DateTime occurredOnUtc = DateTime.UtcNow; + + // Act + ScheduledJobExecutionStoppedDomainEvent domainEvent = _scheduledJobExecutionStoppedDomainEventFixture.Create(id, scheduledJobId, occurredOnUtc); + + // Assert + Assert.Equal(id, domainEvent.Id); + Assert.Equal(scheduledJobId, domainEvent.ScheduledJobId); + Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc); + Assert.IsType(domainEvent, exactMatch: false); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobFiredDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobFiredDomainEventTests.cs new file mode 100644 index 00000000..4b4569e5 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobFiredDomainEventTests.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobFiredDomainEventTests +{ + private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new(); + private readonly ScheduledJobFiredDomainEventFixture _scheduledJobFiredDomainEventFixture = new(); + + [Fact] + public void Constructor_WhenCalled_ShouldSetAllProperties() + { + // Arrange + Guid id = Guid.NewGuid(); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + DateTime occurredOnUtc = DateTime.UtcNow; + + // Act + ScheduledJobFiredDomainEvent domainEvent = _scheduledJobFiredDomainEventFixture.Create(id, scheduledJobId, occurredOnUtc); + + // Assert + Assert.Equal(id, domainEvent.Id); + Assert.Equal(scheduledJobId, domainEvent.ScheduledJobId); + Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc); + Assert.IsType(domainEvent, exactMatch: false); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobRemovedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobRemovedDomainEventTests.cs new file mode 100644 index 00000000..3854ecb9 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/Events/ScheduledJobRemovedDomainEventTests.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobRemovedDomainEventTests +{ + private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new(); + private readonly ScheduledJobRemovedDomainEventFixture _scheduledJobRemovedDomainEventFixture = new(); + + [Fact] + public void Constructor_WhenCalled_ShouldSetAllProperties() + { + // Arrange + Guid id = Guid.NewGuid(); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + DateTime occurredOnUtc = DateTime.UtcNow; + + // Act + ScheduledJobRemovedDomainEvent domainEvent = _scheduledJobRemovedDomainEventFixture.Create(id, scheduledJobId, occurredOnUtc); + + // Assert + Assert.Equal(id, domainEvent.Id); + Assert.Equal(scheduledJobId, domainEvent.ScheduledJobId); + Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc); + Assert.IsType(domainEvent, exactMatch: false); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ScheduledJobTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ScheduledJobTests.cs new file mode 100644 index 00000000..fdb4b954 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ScheduledJobTests.cs @@ -0,0 +1,406 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobTests +{ + private readonly ScheduledJobFixture _scheduledJobFixture = new(); + private readonly IntervalScheduleFixture _intervalScheduleFixture = new(); + private readonly DailyScheduleFixture _dailyScheduleFixture = new(); + private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + + [Fact] + public void Create_WhenCalledWithValidData_ShouldCreateAddedScheduledJobWithAllPropertiesSet() + { + // Arrange + string name = "Scan libraries every hour"; + ScheduledTaskType taskType = ScheduledTaskType.ScanMediaLibraries; + IntervalSchedule schedule = _intervalScheduleFixture.Create(intervalMinutes: 60); + UserId ownerUserId = _userIdFixture.Create(); + + // Act + Result result = ScheduledJob.Create(name, taskType, schedule, ownerUserId); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(name, result.Value.Name); + Assert.Equal(taskType, result.Value.TaskType); + Assert.Equal(schedule, result.Value.Schedule); + Assert.Equal(ownerUserId, result.Value.OwnerUserId); + Assert.Equal(ScheduledJobStatus.Added, result.Value.Status); + Assert.False(result.Value.LastStartedOnUtc.HasValue); + Assert.False(result.Value.LastCompletedOnUtc.HasValue); + Assert.Empty(result.Value.GetDomainEvents()); + } + + [Fact] + public void Create_WhenCalledTwice_ShouldGenerateDistinctIds() + { + // Act + Result firstResult = ScheduledJob.Create("Job 1", ScheduledTaskType.ScanMediaLibraries, _intervalScheduleFixture.Create(), _userIdFixture.Create()); + Result secondResult = ScheduledJob.Create("Job 2", ScheduledTaskType.ScanMediaLibraries, _intervalScheduleFixture.Create(), _userIdFixture.Create()); + + // Assert + Assert.False(firstResult.IsFailure); + Assert.False(secondResult.IsFailure); + Assert.NotEqual(firstResult.Value.Id.Value, secondResult.Value.Id.Value); + } + + [Theory] + [InlineData(null)] // null name + [InlineData("")] // empty name + [InlineData(" ")] // whitespace name + public void Create_WhenNameIsEmptyOrWhitespace_ShouldReturnError(string? name) + { + // Act + Result result = ScheduledJob.Create(name!, ScheduledTaskType.ScanMediaLibraries, _intervalScheduleFixture.Create(), _userIdFixture.Create()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Scheduling.ScheduledJobNameCannotBeEmpty, result.FirstError); + } + + [Fact] + public void Create_WhenCalledWithPreExistingIdAndData_ShouldCreateScheduledJobWithThatIdAndState() + { + // Arrange + Guid id = Guid.NewGuid(); + DateTime lastStartedOnUtc = DateTime.UtcNow.AddHours(-1); + DateTime lastCompletedOnUtc = DateTime.UtcNow.AddMinutes(-30); + + // Act + Result result = ScheduledJob.Create( + _scheduledJobIdFixture.Create(id), + "Daily cleanup", + ScheduledTaskType.CleanTemporaryFiles, + _dailyScheduleFixture.Create(hour: 3, minute: 0), + _userIdFixture.Create(), + ScheduledJobStatus.Active, + Optional.Some(lastStartedOnUtc), + Optional.Some(lastCompletedOnUtc)); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(id, result.Value.Id.Value); + Assert.Equal(ScheduledJobStatus.Active, result.Value.Status); + Assert.Equal(lastStartedOnUtc, result.Value.LastStartedOnUtc.Value); + Assert.Equal(lastCompletedOnUtc, result.Value.LastCompletedOnUtc.Value); + } + + [Fact] + public void Add_WhenStatusIsAdded_ShouldSucceedAndRaiseAddedEvent() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(); + + // Act + Result result = scheduledJob.Add(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Success, result.Value); + Assert.Equal(ScheduledJobStatus.Added, scheduledJob.Status); + ScheduledJobAddedDomainEvent addedEvent = Assert.IsType(Assert.Single(scheduledJob.GetDomainEvents())); + Assert.Equal(scheduledJob.Id, addedEvent.ScheduledJobId); + Assert.NotEqual(default, addedEvent.OccurredOnUtc); + } + + [Theory] + [InlineData(ScheduledJobStatus.Active)] // cannot add an already active scheduled job + [InlineData(ScheduledJobStatus.Running)] // cannot add a running scheduled job + [InlineData(ScheduledJobStatus.Completed)] // cannot add a completed scheduled job + public void Add_WhenStatusIsNotAdded_ShouldReturnError(ScheduledJobStatus status) + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(status: status); + + // Act + Result result = scheduledJob.Add(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Scheduling.ScheduledJobCycleAlreadyStarted, result.FirstError); + Assert.Empty(scheduledJob.GetDomainEvents()); + } + + [Fact] + public void StartCycle_WhenStatusIsAdded_ShouldTransitionToActiveAndRaiseCycleStartedEvent() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(); + + // Act + Result result = scheduledJob.StartCycle(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Success, result.Value); + Assert.Equal(ScheduledJobStatus.Active, scheduledJob.Status); + ScheduledJobCycleStartedDomainEvent cycleStartedEvent = Assert.IsType(Assert.Single(scheduledJob.GetDomainEvents())); + Assert.Equal(scheduledJob.Id, cycleStartedEvent.ScheduledJobId); + } + + [Theory] + [InlineData(ScheduledJobStatus.Active)] // cannot start an already active execution cycle + [InlineData(ScheduledJobStatus.Running)] // cannot start a running execution cycle + public void StartCycle_WhenCycleAlreadyStarted_ShouldReturnError(ScheduledJobStatus status) + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(status: status); + + // Act + Result result = scheduledJob.StartCycle(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Scheduling.ScheduledJobCycleAlreadyStarted, result.FirstError); + Assert.Equal(status, scheduledJob.Status); + Assert.Empty(scheduledJob.GetDomainEvents()); + } + + [Fact] + public void StopCycle_WhenStatusIsActive_ShouldTransitionToAddedAndRaiseCycleStoppedEvent() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(); + scheduledJob.StartCycle(); + scheduledJob.GetDomainEvents(); + + // Act + Result result = scheduledJob.StopCycle(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Success, result.Value); + Assert.Equal(ScheduledJobStatus.Added, scheduledJob.Status); + ScheduledJobCycleStoppedDomainEvent cycleStoppedEvent = Assert.IsType(Assert.Single(scheduledJob.GetDomainEvents())); + Assert.Equal(scheduledJob.Id, cycleStoppedEvent.ScheduledJobId); + } + + [Fact] + public void StopCycle_WhenStatusIsRunning_ShouldTransitionToAddedAndRaiseExecutionStoppedEvent() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(); + scheduledJob.StartCycle(); + scheduledJob.MarkExecutionStarted(isCycleRun: true); + scheduledJob.GetDomainEvents(); + + // Act + Result result = scheduledJob.StopCycle(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Success, result.Value); + Assert.Equal(ScheduledJobStatus.Added, scheduledJob.Status); + Assert.True(scheduledJob.LastCompletedOnUtc.HasValue); + ScheduledJobExecutionStoppedDomainEvent executionStoppedEvent = Assert.IsType(Assert.Single(scheduledJob.GetDomainEvents())); + Assert.Equal(scheduledJob.Id, executionStoppedEvent.ScheduledJobId); + } + + [Theory] + [InlineData(ScheduledJobStatus.Added)] // cannot stop a cycle that was never started + [InlineData(ScheduledJobStatus.Completed)] // cannot stop a finished one time execution + public void StopCycle_WhenCycleWasNeverStarted_ShouldReturnError(ScheduledJobStatus status) + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(status: status); + + // Act + Result result = scheduledJob.StopCycle(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Scheduling.ScheduledJobNotStarted, result.FirstError); + Assert.Equal(status, scheduledJob.Status); + Assert.Empty(scheduledJob.GetDomainEvents()); + } + + [Fact] + public void Fire_WhenStatusIsNotRunning_ShouldSucceedAndRaiseFiredEvent() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(); + + // Act + Result result = scheduledJob.Fire(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Success, result.Value); + ScheduledJobFiredDomainEvent firedEvent = Assert.IsType(Assert.Single(scheduledJob.GetDomainEvents())); + Assert.Equal(scheduledJob.Id, firedEvent.ScheduledJobId); + } + + [Fact] + public void Fire_WhenStatusIsRunning_ShouldReturnError() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(); + scheduledJob.StartCycle(); + scheduledJob.MarkExecutionStarted(isCycleRun: true); + scheduledJob.GetDomainEvents(); + + // Act + Result result = scheduledJob.Fire(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Scheduling.ScheduledJobAlreadyRunning, result.FirstError); + Assert.Empty(scheduledJob.GetDomainEvents()); + } + + [Fact] + public void Remove_WhenCalled_ShouldSucceedAndRaiseRemovedEvent() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(); + + // Act + Result result = scheduledJob.Remove(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Success, result.Value); + ScheduledJobRemovedDomainEvent removedEvent = Assert.IsType(Assert.Single(scheduledJob.GetDomainEvents())); + Assert.Equal(scheduledJob.Id, removedEvent.ScheduledJobId); + } + + [Theory] + [InlineData(true)] // cycle run + [InlineData(false)] // one time run + public void MarkExecutionStarted_WhenStatusIsNotRunning_ShouldTransitionToRunningAndRaiseExecutionStartedEvent(bool isCycleRun) + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(); + + // Act + Result result = scheduledJob.MarkExecutionStarted(isCycleRun); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Success, result.Value); + Assert.Equal(ScheduledJobStatus.Running, scheduledJob.Status); + Assert.True(scheduledJob.LastStartedOnUtc.HasValue); + ScheduledJobExecutionStartedDomainEvent startedEvent = Assert.IsType(Assert.Single(scheduledJob.GetDomainEvents())); + Assert.Equal(scheduledJob.Id, startedEvent.ScheduledJobId); + Assert.Equal(scheduledJob.TaskType, startedEvent.TaskType); + Assert.Equal(isCycleRun, startedEvent.IsCycleRun); + Assert.NotEqual(Guid.Empty, startedEvent.RunId); + } + + [Fact] + public void MarkExecutionStarted_WhenStatusIsRunning_ShouldReturnError() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(); + scheduledJob.StartCycle(); + scheduledJob.MarkExecutionStarted(isCycleRun: true); + scheduledJob.GetDomainEvents(); + + // Act + Result result = scheduledJob.MarkExecutionStarted(isCycleRun: true); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Scheduling.ScheduledJobAlreadyRunning, result.FirstError); + Assert.Empty(scheduledJob.GetDomainEvents()); + } + + [Theory] + [InlineData(true)] // a cycle run returns the scheduled job to its active status + [InlineData(false)] // a one time execution completes the scheduled job + public void MarkExecutionCompleted_WhenStatusIsRunning_ShouldTransitionStatusAndRaiseExecutionCompletedEvent(bool isCycleRun) + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(); + scheduledJob.StartCycle(); + scheduledJob.MarkExecutionStarted(isCycleRun); + scheduledJob.GetDomainEvents(); + + // Act + Result result = scheduledJob.MarkExecutionCompleted(isCycleRun); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Success, result.Value); + Assert.Equal(isCycleRun ? ScheduledJobStatus.Active : ScheduledJobStatus.Completed, scheduledJob.Status); + Assert.True(scheduledJob.LastCompletedOnUtc.HasValue); + ScheduledJobExecutionCompletedDomainEvent completedEvent = Assert.IsType(Assert.Single(scheduledJob.GetDomainEvents())); + Assert.Equal(scheduledJob.Id, completedEvent.ScheduledJobId); + Assert.Equal(scheduledJob.TaskType, completedEvent.TaskType); + Assert.Equal(isCycleRun, completedEvent.IsCycleRun); + Assert.NotEqual(Guid.Empty, completedEvent.RunId); + } + + [Theory] + [InlineData(ScheduledJobStatus.Added)] // cannot complete an execution that never started + [InlineData(ScheduledJobStatus.Active)] // cannot complete an execution that never started + [InlineData(ScheduledJobStatus.Completed)] // cannot complete an already completed execution + public void MarkExecutionCompleted_WhenStatusIsNotRunning_ShouldReturnError(ScheduledJobStatus status) + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(status: status); + + // Act + Result result = scheduledJob.MarkExecutionCompleted(isCycleRun: true); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Scheduling.CanOnlyCompleteRunningScheduledJob, result.FirstError); + Assert.Empty(scheduledJob.GetDomainEvents()); + } + + [Fact] + public void MarkExecutionCompleted_WhenLoadedFromStorageWithoutActiveRunId_ShouldReturnError() + { + // Arrange + // A scheduled job loaded from the storage medium with a running status has no active run id tracked by the aggregate. + ScheduledJob scheduledJob = _scheduledJobFixture.Create( + id: Guid.NewGuid(), + status: ScheduledJobStatus.Running, + lastStartedOnUtc: DateTime.UtcNow.AddMinutes(-5)); + + // Act + Result result = scheduledJob.MarkExecutionCompleted(isCycleRun: true); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Scheduling.CanOnlyCompleteRunningScheduledJob, result.FirstError); + Assert.Empty(scheduledJob.GetDomainEvents()); + } + + [Fact] + public void MarkExecutionCompleted_WhenCycleRunAfterExecutionStarted_ShouldAllowTheNextCycleRunToStart() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(); + scheduledJob.StartCycle(); + scheduledJob.MarkExecutionStarted(isCycleRun: true); + scheduledJob.MarkExecutionCompleted(isCycleRun: true); + + // Act + Result startNextExecutionResult = scheduledJob.MarkExecutionStarted(isCycleRun: true); + // Assert + Assert.False(startNextExecutionResult.IsFailure); + Assert.Equal(ScheduledJobStatus.Running, scheduledJob.Status); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/DailyScheduleTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/DailyScheduleTests.cs new file mode 100644 index 00000000..3f50d8fe --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/DailyScheduleTests.cs @@ -0,0 +1,155 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DailyScheduleTests +{ + [Fact] + public void Create_WhenCalledWithValidHourAndMinute_ShouldCreateDailyScheduleWithAllPropertiesSet() + { + // Act + Result result = DailySchedule.Create(8, 30); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(8, result.Value.Hour); + Assert.Equal(30, result.Value.Minute); + Assert.Equal(ScheduleType.DailyAtHourAndMinute, result.Value.ScheduleType); + } + + [Theory] + [InlineData(-1)] // hour below the allowed range + [InlineData(24)] // hour above the allowed range + public void Create_WhenHourIsOutOfRange_ShouldReturnError(int hour) + { + // Act + Result result = DailySchedule.Create(hour, 0); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Scheduling.HourMustBeBetweenZeroAndTwentyThree, result.FirstError); + } + + [Theory] + [InlineData(-1)] // minute below the allowed range + [InlineData(60)] // minute above the allowed range + public void Create_WhenMinuteIsOutOfRange_ShouldReturnError(int minute) + { + // Act + Result result = DailySchedule.Create(8, minute); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Scheduling.MinuteMustBeBetweenZeroAndFiftyNine, result.FirstError); + } + + [Fact] + public void Create_WhenCalledWithLowerBoundaryValues_ShouldCreateDailySchedule() + { + // Act + Result result = DailySchedule.Create(0, 0); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(0, result.Value.Hour); + Assert.Equal(0, result.Value.Minute); + } + + [Fact] + public void Create_WhenCalledWithUpperBoundaryValues_ShouldCreateDailySchedule() + { + // Act + Result result = DailySchedule.Create(23, 59); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(23, result.Value.Hour); + Assert.Equal(59, result.Value.Minute); + } + + [Fact] + public void GetDelayUntilNextExecution_WhenNextRunIsLaterToday_ShouldReturnDelayUntilNextRun() + { + // Arrange + DailySchedule schedule = DailySchedule.Create(12, 30).Value; + DateTime utcNow = new(2026, 1, 1, 10, 0, 0, DateTimeKind.Utc); + + // Act + TimeSpan delay = schedule.GetDelayUntilNextExecution(utcNow, TimeZoneInfo.Utc); + + // Assert + Assert.Equal(TimeSpan.FromHours(2.5), delay); + } + + [Fact] + public void GetDelayUntilNextExecution_WhenNextRunAlreadyPassedToday_ShouldReturnDelayUntilTomorrow() + { + // Arrange + DailySchedule schedule = DailySchedule.Create(8, 0).Value; + DateTime utcNow = new(2026, 1, 1, 10, 0, 0, DateTimeKind.Utc); + + // Act + TimeSpan delay = schedule.GetDelayUntilNextExecution(utcNow, TimeZoneInfo.Utc); + + // Assert + Assert.Equal(TimeSpan.FromHours(22), delay); + } + + [Fact] + public void GetDelayUntilNextExecution_WhenNextRunEqualsNow_ShouldReturnDelayUntilTomorrow() + { + // Arrange + DailySchedule schedule = DailySchedule.Create(10, 0).Value; + DateTime utcNow = new(2026, 1, 1, 10, 0, 0, DateTimeKind.Utc); + + // Act + TimeSpan delay = schedule.GetDelayUntilNextExecution(utcNow, TimeZoneInfo.Utc); + + // Assert + Assert.Equal(TimeSpan.FromDays(1), delay); + } + + [Fact] + public void Equals_WhenHourAndMinuteAreEqual_ShouldReturnTrue() + { + // Act + bool areEqual = DailySchedule.Create(8, 30).Value.Equals(DailySchedule.Create(8, 30).Value); + + // Assert + Assert.True(areEqual); + } + + [Theory] + [InlineData(9, 30)] // different hour + [InlineData(8, 31)] // different minute + public void Equals_WhenHourOrMinuteDiffer_ShouldReturnFalse(int hour, int minute) + { + // Act + bool areEqual = DailySchedule.Create(8, 30).Value.Equals(DailySchedule.Create(hour, minute).Value); + + // Assert + Assert.False(areEqual); + } + + [Fact] + public void GetHashCode_WhenHourAndMinuteAreEqual_ShouldReturnEqualHashCodes() + { + // Act + int firstHashCode = DailySchedule.Create(8, 30).Value.GetHashCode(); + int secondHashCode = DailySchedule.Create(8, 30).Value.GetHashCode(); + + // Assert + Assert.Equal(firstHashCode, secondHashCode); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/IntervalScheduleTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/IntervalScheduleTests.cs new file mode 100644 index 00000000..c91a84f3 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/IntervalScheduleTests.cs @@ -0,0 +1,88 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class IntervalScheduleTests +{ + [Fact] + public void Create_WhenCalledWithValidInterval_ShouldCreateIntervalScheduleWithAllPropertiesSet() + { + // Act + Result result = IntervalSchedule.Create(60); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(60, result.Value.IntervalMinutes); + Assert.Equal(ScheduleType.WithIntervalInMinutes, result.Value.ScheduleType); + } + + [Theory] + [InlineData(0)] // interval of zero + [InlineData(-1)] // negative interval + [InlineData(-100)] // negative interval far from zero + public void Create_WhenIntervalIsNotPositive_ShouldReturnError(int intervalMinutes) + { + // Act + Result result = IntervalSchedule.Create(intervalMinutes); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Scheduling.IntervalMinutesMustBePositive, result.FirstError); + } + + [Fact] + public void Create_WhenCalledWithOneMinuteInterval_ShouldCreateIntervalSchedule() + { + // Act + Result result = IntervalSchedule.Create(1); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(1, result.Value.IntervalMinutes); + } + + [Fact] + public void GetDelayUntilNextExecution_WhenCalled_ShouldReturnTheIntervalInMinutes() + { + // Arrange + IntervalSchedule schedule = IntervalSchedule.Create(45).Value; + DateTime utcNow = new(2026, 1, 1, 10, 0, 0, DateTimeKind.Utc); + + // Act + TimeSpan delay = schedule.GetDelayUntilNextExecution(utcNow, TimeZoneInfo.Utc); + + // Assert + Assert.Equal(TimeSpan.FromMinutes(45), delay); + } + + [Fact] + public void Equals_WhenIntervalsAreEqual_ShouldReturnTrue() + { + // Act + bool areEqual = IntervalSchedule.Create(60).Value.Equals(IntervalSchedule.Create(60).Value); + + // Assert + Assert.True(areEqual); + } + + [Fact] + public void Equals_WhenIntervalsDiffer_ShouldReturnFalse() + { + // Act + bool areEqual = IntervalSchedule.Create(60).Value.Equals(IntervalSchedule.Create(120).Value); + + // Assert + Assert.False(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/OnceAtStartupScheduleTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/OnceAtStartupScheduleTests.cs new file mode 100644 index 00000000..15d706d8 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/OnceAtStartupScheduleTests.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class OnceAtStartupScheduleTests +{ + private readonly OnceAtStartupScheduleFixture _onceAtStartupScheduleFixture = new(); + + [Fact] + public void Create_WhenCalled_ShouldCreateOnceAtStartupSchedule() + { + // Act + OnceAtStartupSchedule schedule = _onceAtStartupScheduleFixture.Create(); + + // Assert + Assert.Equal(ScheduleType.OnceAtStartup, schedule.ScheduleType); + } + + [Fact] + public void GetDelayUntilNextExecution_WhenCalled_ShouldReturnTheMaximumDelay() + { + // Arrange + OnceAtStartupSchedule schedule = _onceAtStartupScheduleFixture.Create(); + DateTime utcNow = new(2026, 1, 1, 10, 0, 0, DateTimeKind.Utc); + + // Act + TimeSpan delay = schedule.GetDelayUntilNextExecution(utcNow, TimeZoneInfo.Utc); + + // Assert + Assert.Equal(TimeSpan.MaxValue, delay); + } + + [Fact] + public void Equals_WhenBothAreOnceAtStartupSchedules_ShouldReturnTrue() + { + // Act + bool areEqual = _onceAtStartupScheduleFixture.Create().Equals(_onceAtStartupScheduleFixture.Create()); + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/ScheduledJobIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/ScheduledJobIdTests.cs new file mode 100644 index 00000000..a40f7a9e --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/ScheduledJobIdTests.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobIdTests +{ + private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new(); + + [Fact] + public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue() + { + // Act + ScheduledJobId scheduledJobId = ScheduledJobId.CreateUnique(); + + // Assert + Assert.NotNull(scheduledJobId); + Assert.NotEqual(default, scheduledJobId.Value); + } + + [Fact] + public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue() + { + // Arrange + Guid value = Guid.NewGuid(); + + // Act + ScheduledJobId scheduledJobId = ScheduledJobId.Create(value); + + // Assert + Assert.Equal(value, scheduledJobId.Value); + } + + [Fact] + public void Equals_WithSameValue_ShouldReturnTrue() + { + // Arrange + Guid value = Guid.NewGuid(); + ScheduledJobId firstId = _scheduledJobIdFixture.Create(value); + ScheduledJobId secondId = _scheduledJobIdFixture.Create(value); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + ScheduledJobId firstId = _scheduledJobIdFixture.Create(); + ScheduledJobId secondId = _scheduledJobIdFixture.Create(); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Progress/MediaLibraryScanProgressHubTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Progress/MediaLibraryScanProgressHubTests.cs index 89c3566d..6acf31f3 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Progress/MediaLibraryScanProgressHubTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Progress/MediaLibraryScanProgressHubTests.cs @@ -4,6 +4,7 @@ using Microsoft.AspNetCore.SignalR; using NSubstitute; using System; using System.Diagnostics.CodeAnalysis; +using System.Security.Claims; using System.Threading; using System.Threading.Tasks; #endregion @@ -17,9 +18,9 @@ namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning. public class MediaLibraryScanProgressHubTests { [Fact] - public async Task SubscribeToScan_WhenCalled_ShouldAddTheConnectionToTheScanGroup() + public async Task SubscribeToScan_WhenCalled_ShouldAddTheConnectionToTheGroupOfTheAuthenticatedUser() { - // Arrange + // Arrange. MediaLibraryScanProgressHub sut = new(); HubCallerContext context = Substitute.For(); context.ConnectionId.Returns("connection-1"); @@ -28,11 +29,56 @@ public class MediaLibraryScanProgressHubTests sut.Groups = groupManager; Guid scanId = Guid.NewGuid(); Guid userId = Guid.NewGuid(); + // The user is always taken from the authenticated connection, never from the client. + ClaimsPrincipal user = new(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, userId.ToString())])); + context.User.Returns(user); - // Act - await sut.SubscribeToScan(scanId, userId); + // Act. + await sut.SubscribeToScan(scanId); - // Assert + // Assert. await groupManager.Received(1).AddToGroupAsync("connection-1", $"{scanId}-{userId}", CancellationToken.None); } + + [Fact] + public async Task SubscribeToScan_WhenUserClaimIsMissing_ShouldNotAddTheConnectionToAnyGroup() + { + // Arrange. + MediaLibraryScanProgressHub sut = new(); + HubCallerContext context = Substitute.For(); + context.ConnectionId.Returns("connection-1"); + IGroupManager groupManager = Substitute.For(); + sut.Context = context; + sut.Groups = groupManager; + Guid scanId = Guid.NewGuid(); + ClaimsPrincipal user = new(new ClaimsIdentity()); + context.User.Returns(user); + + // Act. + await sut.SubscribeToScan(scanId); + + // Assert. + await groupManager.DidNotReceive().AddToGroupAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task SubscribeToScan_WhenUserIdClaimIsNotAGuid_ShouldNotAddTheConnectionToAnyGroup() + { + // Arrange. + MediaLibraryScanProgressHub sut = new(); + HubCallerContext context = Substitute.For(); + context.ConnectionId.Returns("connection-1"); + IGroupManager groupManager = Substitute.For(); + sut.Context = context; + sut.Groups = groupManager; + Guid scanId = Guid.NewGuid(); + ClaimsPrincipal user = new(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, "not-a-guid")])); + context.User.Returns(user); + + // Act. + await sut.SubscribeToScan(scanId); + + // Assert. + await groupManager.DidNotReceive().AddToGroupAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobRuntimeRegistryTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobRuntimeRegistryTests.cs new file mode 100644 index 00000000..55b6b16b --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobRuntimeRegistryTests.cs @@ -0,0 +1,218 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Infrastructure.Core.Scheduling.Execution; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Execution; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobRuntimeRegistryTests +{ + private readonly ScheduledJobRuntimeRegistry _sut = new(); + private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new(); + + [Fact] + public void TryStartCycle_WhenNoCycleIsRunning_ShouldReturnTrue() + { + // Arrange + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + using CancellationTokenSource cycleCancellationTokenSource = new(); + + // Act + bool result = _sut.TryStartCycle(scheduledJobId, cycleCancellationTokenSource); + + // Assert + Assert.True(result); + } + + [Fact] + public void TryStartCycle_WhenCycleIsAlreadyRunning_ShouldReturnFalse() + { + // Arrange + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + using CancellationTokenSource firstCancellationTokenSource = new(); + using CancellationTokenSource secondCancellationTokenSource = new(); + _sut.TryStartCycle(scheduledJobId, firstCancellationTokenSource); + + // Act + bool result = _sut.TryStartCycle(scheduledJobId, secondCancellationTokenSource); + + // Assert + Assert.False(result); + } + + [Fact] + public void StopCycle_WhenCycleIsRunning_ShouldCancelTheCycleAndAllowRestartingIt() + { + // Arrange + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + using CancellationTokenSource cycleCancellationTokenSource = new(); + _sut.TryStartCycle(scheduledJobId, cycleCancellationTokenSource); + + // Act + _sut.StopCycle(scheduledJobId); + + // Assert + Assert.True(cycleCancellationTokenSource.IsCancellationRequested); + using CancellationTokenSource restartedCycleCancellationTokenSource = new(); + Assert.True(_sut.TryStartCycle(scheduledJobId, restartedCycleCancellationTokenSource)); + } + + [Fact] + public void StopCycle_WhenNoCycleIsRunning_ShouldNotThrow() + { + // Arrange + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + + // Act + _sut.StopCycle(scheduledJobId); + + // Assert + Assert.True(true); + } + + [Fact] + public void TryAcquireRunSlot_WhenNoExecutionIsRunning_ShouldReturnTrueAndThenFalseWhileHeld() + { + // Arrange + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + + // Act + bool firstAcquire = _sut.TryAcquireRunSlot(scheduledJobId); + bool secondAcquire = _sut.TryAcquireRunSlot(scheduledJobId); + + // Assert + Assert.True(firstAcquire); + Assert.False(secondAcquire); + } + + [Fact] + public void ReleaseRunSlot_WhenSlotWasAcquired_ShouldAllowAcquiringItAgain() + { + // Arrange + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + _sut.TryAcquireRunSlot(scheduledJobId); + + // Act + _sut.ReleaseRunSlot(scheduledJobId); + + // Assert + Assert.True(_sut.TryAcquireRunSlot(scheduledJobId)); + } + + [Fact] + public void TryAcquireRunSlot_AfterReleasingTheSlot_ShouldReturnTrue() + { + // Arrange + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + _sut.TryAcquireRunSlot(scheduledJobId); + _sut.ReleaseRunSlot(scheduledJobId); + + // Act + bool result = _sut.TryAcquireRunSlot(scheduledJobId); + + // Assert + Assert.True(result); + } + + [Fact] + public void HasActiveCycle_WhenCycleIsRunning_ShouldReturnTrue() + { + // Arrange + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + using CancellationTokenSource cycleCancellationTokenSource = new(); + _sut.TryStartCycle(scheduledJobId, cycleCancellationTokenSource); + + // Act + bool result = _sut.HasActiveCycle(scheduledJobId); + + // Assert + Assert.True(result); + } + + [Fact] + public void HasActiveCycle_WhenNoCycleIsRunning_ShouldReturnFalse() + { + // Arrange + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + + // Act + bool result = _sut.HasActiveCycle(scheduledJobId); + + // Assert + Assert.False(result); + } + + [Fact] + public void HasActiveCycle_AfterTheCycleWasStopped_ShouldReturnFalse() + { + // Arrange + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + using CancellationTokenSource cycleCancellationTokenSource = new(); + _sut.TryStartCycle(scheduledJobId, cycleCancellationTokenSource); + _sut.StopCycle(scheduledJobId); + + // Act + bool result = _sut.HasActiveCycle(scheduledJobId); + + // Assert + Assert.False(result); + } + + [Fact] + public void EndCycle_WhenCalledWithTheOwnedTokenSource_ShouldCancelItAndClearTheCycle() + { + // Arrange + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + using CancellationTokenSource cycleCancellationTokenSource = new(); + _sut.TryStartCycle(scheduledJobId, cycleCancellationTokenSource); + + // Act + _sut.EndCycle(scheduledJobId, cycleCancellationTokenSource); + + // Assert + Assert.True(cycleCancellationTokenSource.IsCancellationRequested); + Assert.False(_sut.HasActiveCycle(scheduledJobId)); + } + + [Fact] + public void EndCycle_WhenTheCycleWasReplacedByANewerOne_ShouldNotCancelTheNewerCycle() + { + // Arrange + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + using CancellationTokenSource oldCycleCancellationTokenSource = new(); + using CancellationTokenSource newCycleCancellationTokenSource = new(); + _sut.TryStartCycle(scheduledJobId, oldCycleCancellationTokenSource); + _sut.StopCycle(scheduledJobId); + _sut.TryStartCycle(scheduledJobId, newCycleCancellationTokenSource); + + // Act + _sut.EndCycle(scheduledJobId, oldCycleCancellationTokenSource); + + // Assert + Assert.True(oldCycleCancellationTokenSource.IsCancellationRequested); + Assert.False(newCycleCancellationTokenSource.IsCancellationRequested); + Assert.True(_sut.HasActiveCycle(scheduledJobId)); + } + + [Fact] + public void EndCycle_WhenNoCycleIsRegistered_ShouldStillCancelTheOwnedTokenSource() + { + // Arrange + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + using CancellationTokenSource cycleCancellationTokenSource = new(); + + // Act + _sut.EndCycle(scheduledJobId, cycleCancellationTokenSource); + + // Assert + Assert.True(cycleCancellationTokenSource.IsCancellationRequested); + Assert.False(_sut.HasActiveCycle(scheduledJobId)); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobSchedulerJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobSchedulerJobTests.cs new file mode 100644 index 00000000..63b116b2 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobSchedulerJobTests.cs @@ -0,0 +1,1132 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.Entities.Themes; +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; +using Lumina.Application.Common.DataAccess.Repositories.Themes; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Themes; +using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using Lumina.Infrastructure.Core.Scheduling.Execution; +using Lumina.Infrastructure.Core.Themes; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Execution; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobSchedulerJobTests +{ + private readonly IServiceScopeFactory _mockServiceScopeFactory; + private readonly IServiceScope _mockServiceScope; + private readonly IServiceProvider _mockServiceProvider; + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IScheduledJobRepository _mockScheduledJobRepository; + private readonly IScheduledJobExecutionRepository _mockScheduledJobExecutionRepository; + private readonly IDomainEventPublisher _mockDomainEventPublisher; + private readonly IScheduledTaskExecutorFactory _mockTaskExecutorFactory; + private readonly IScheduledTaskExecutor _mockTaskExecutor; + private readonly ScheduledJobRuntimeRegistry _runtimeRegistry; + private readonly ScheduledJobSchedulerJob _sut; + private readonly Dictionary _services; + private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new(); + private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new(); + private readonly ScheduledJobExecutionEntityFixture _scheduledJobExecutionEntityFixture = new(); + private readonly ScheduledJobFixture _scheduledJobFixture = new(); + private readonly IntervalScheduleFixture _intervalScheduleFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ScheduledJobSchedulerJobTests() + { + _services = []; + _mockServiceScopeFactory = Substitute.For(); + _mockServiceScope = Substitute.For(); + _mockServiceProvider = Substitute.For(); + _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); + _mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope); + _mockServiceScopeFactory.CreateAsyncScope().Returns(new AsyncServiceScope(_mockServiceScope)); + + _mockUnitOfWork = Substitute.For(); + _mockScheduledJobRepository = Substitute.For(); + _mockScheduledJobExecutionRepository = Substitute.For(); + _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); + _mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); + _mockScheduledJobExecutionRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); + + _mockDomainEventPublisher = Substitute.For(); + _mockTaskExecutorFactory = Substitute.For(); + _mockTaskExecutor = Substitute.For(); + _mockTaskExecutor.ExecutePayloadAsync(Arg.Any(), Arg.Any()).Returns(Result.Success); + _mockTaskExecutorFactory.CreateExecutor(Arg.Any()).Returns(_mockTaskExecutor); + + _services[typeof(IUnitOfWork)] = _mockUnitOfWork; + _services[typeof(IDomainEventPublisher)] = _mockDomainEventPublisher; + _services[typeof(IScheduledTaskExecutorFactory)] = _mockTaskExecutorFactory; + _mockServiceProvider.GetService(Arg.Any()) + .Returns(callInfo => _services.TryGetValue((Type)callInfo[0]!, out object? service) ? service : null); + + _runtimeRegistry = new ScheduledJobRuntimeRegistry(); + ILogger logger = Substitute.For>(); + _sut = new ScheduledJobSchedulerJob(_runtimeRegistry, logger, _mockServiceScopeFactory); + } + + [Fact] + public async Task StopCycleAsync_WhenCalled_ShouldStopTheRunningCycleInTheRegistry() + { + // Arrange + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + using CancellationTokenSource cycleCancellationTokenSource = new(); + _runtimeRegistry.TryStartCycle(scheduledJobId, cycleCancellationTokenSource); + + // Act + await _sut.StopCycleAsync(scheduledJobId, CancellationToken.None); + + // Assert + Assert.True(cycleCancellationTokenSource.IsCancellationRequested); + } + + [Fact] + public async Task StartCycleAsync_WhenCycleIsAlreadyRunning_ShouldNotStartAnotherCycle() + { + // Arrange + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + using CancellationTokenSource firstCycleCancellationTokenSource = new(); + _runtimeRegistry.TryStartCycle(scheduledJobId, firstCycleCancellationTokenSource); + + // Act + await _sut.StartCycleAsync(scheduledJobId, CancellationToken.None); + // Wait briefly so the fire-and-forget worker, if any, gets a chance to run. + await Task.Delay(150); + + // Assert + using CancellationTokenSource secondCycleCancellationTokenSource = new(); + Assert.False(_runtimeRegistry.TryStartCycle(scheduledJobId, secondCycleCancellationTokenSource)); + } + + [Fact] + public async Task RunOnceAsync_WhenTheJobCannotStart_ShouldNotExecuteThePayload() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + + // Act + await _sut.RunOnceAsync(scheduledJobId, CancellationToken.None); + // Wait briefly so the fire-and-forget worker, if any, gets a chance to run. + await Task.Delay(150); + + // Assert + await _mockTaskExecutor.DidNotReceive().ExecutePayloadAsync(Arg.Any(), Arg.Any()); + Assert.True(_runtimeRegistry.TryAcquireRunSlot(scheduledJobId)); + _runtimeRegistry.ReleaseRunSlot(scheduledJobId); + } + + [Fact] + public async Task ExecuteScheduledJobRunAsync_WhenFiredOnAJobWithoutAnActiveCycle_ShouldCompleteTheJobAsAOneTimeRun() + { + // Arrange + ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60)); + + // Act + await InvokeAsync("ExecuteScheduledJobRunAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockTaskExecutor.Received(1).ExecutePayloadAsync(Arg.Any(), Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => !domainEvent.IsCycleRun), Arg.Any()); + } + + [Fact] + public async Task ExecuteScheduledJobRunAsync_WhenFiredOnAJobWithAnActiveCycle_ShouldCompleteTheJobBackToItsActiveState() + { + // Arrange + ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60)); + using CancellationTokenSource cycleCancellationTokenSource = new(); + _runtimeRegistry.TryStartCycle(scheduledJobId, cycleCancellationTokenSource); + + // Act + await InvokeAsync("ExecuteScheduledJobRunAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockTaskExecutor.Received(1).ExecutePayloadAsync(Arg.Any(), Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.IsCycleRun), Arg.Any()); + Assert.True(_runtimeRegistry.HasActiveCycle(scheduledJobId)); + } + + [Fact] + public async Task RunScheduledJobAsync_WhenTheStartedEventPublishingFails_ShouldReconcileTheInterruptedRunAndReleaseTheRunSlot() + { + // Arrange + ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob, runningJob); + ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); + _mockDomainEventPublisher.When(publisher => publisher.PublishAsync(Arg.Is(_ => true), Arg.Any())) + .Do(_ => throw new InvalidOperationException("publish failed")); + + // Act + await InvokeAsync("RunScheduledJobAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockScheduledJobRepository.Received(1).UpdateAsync(Arg.Is(entity => entity.Status == ScheduledJobStatus.Active), Arg.Any()); + await _mockScheduledJobExecutionRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + Assert.True(_runtimeRegistry.TryAcquireRunSlot(scheduledJobId)); + _runtimeRegistry.ReleaseRunSlot(scheduledJobId); + } + + [Fact] + public async Task ReconcileInterruptedRunAsync_WhenTheOpenExecutionHadAnActiveCycle_ShouldRestoreTheJobToItsActiveState() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); + + // Act + ScheduledJobStatus result = await InvokeAsync("ReconcileInterruptedRunAsync", scheduledJobId, CancellationToken.None); + + // Assert + Assert.Equal(ScheduledJobStatus.Active, result); + await _mockScheduledJobRepository.Received(1).UpdateAsync(Arg.Is(entity => entity.Status == ScheduledJobStatus.Active), Arg.Any()); + await _mockScheduledJobExecutionRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task ReconcileInterruptedRunAsync_WhenTheOpenExecutionHadNoActiveCycle_ShouldRestoreTheJobToItsAddedState() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: false, completedOnUtc: null); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); + + // Act + ScheduledJobStatus result = await InvokeAsync("ReconcileInterruptedRunAsync", scheduledJobId, CancellationToken.None); + + // Assert + Assert.Equal(ScheduledJobStatus.Added, result); + await _mockScheduledJobRepository.Received(1).UpdateAsync(Arg.Is(entity => entity.Status == ScheduledJobStatus.Added), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task ReconcileInterruptedRunAsync_WhenTheJobIsNotRunning_ShouldReturnItsCurrentStatusWithoutReconciling() + { + // Arrange + ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + + // Act + ScheduledJobStatus result = await InvokeAsync("ReconcileInterruptedRunAsync", scheduledJobId, CancellationToken.None); + + // Assert + Assert.Equal(ScheduledJobStatus.Active, result); + await _mockScheduledJobRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task RunCycleWorkerAsync_WhenTheJobHasAOnceAtStartupSchedule_ShouldRunTheTaskOnceAndEndTheCycle() + { + // Arrange + ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.OnceAtStartup); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.OnceAtStartup)); + + // Act + await InvokeAsync("RunCycleWorkerAsync", scheduledJobId, true, CancellationToken.None); + + // Assert + await _mockTaskExecutor.Received(1).ExecutePayloadAsync(Arg.Any(), Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.IsCycleRun), Arg.Any()); + Assert.False(_runtimeRegistry.HasActiveCycle(scheduledJobId)); + } + + [Fact] + public async Task ResumeActiveCyclesAsync_WhenAnActiveOnceAtStartupJobExists_ShouldResumeItsCycleAndFireTheTask() + { + // Arrange + ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.OnceAtStartup); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); + _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(new[] { activeJob }); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.OnceAtStartup)); + + // Act + await InvokeAsync("ResumeActiveCyclesAsync", CancellationToken.None); + await WaitUntilAsync(() => _mockTaskExecutor.ReceivedCalls().Count() > 0); + + // Assert + await _mockTaskExecutor.Received(1).ExecutePayloadAsync(Arg.Any(), Arg.Any()); + Assert.False(_runtimeRegistry.HasActiveCycle(scheduledJobId)); + } + + [Fact] + public async Task SynchronizeBundledThemesIfNeededAsync_WhenTheScheduledJobsCannotBeRead_ShouldNotSynchronizeTheThemes() + { + // Arrange + Error error = Error.Failure("ScheduledJobs.NotFound", "Failed to read the scheduled jobs"); + _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(error); + IThemeService mockThemeService = Substitute.For(); + _services[typeof(IThemeService)] = mockThemeService; + + // Act + await InvokeAsync("SynchronizeBundledThemesIfNeededAsync", CancellationToken.None); + + // Assert + mockThemeService.DidNotReceive().GetBundledThemeArchivePaths(); + } + + [Fact] + public async Task SynchronizeBundledThemesIfNeededAsync_WhenAnActiveRepairThemesJobExists_ShouldNotSynchronizeTheThemes() + { + // Arrange + ScheduledJobEntity repairThemesJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60, taskType: ScheduledTaskType.RepairThemes); + _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(new[] { repairThemesJob }); + IThemeService mockThemeService = Substitute.For(); + _services[typeof(IThemeService)] = mockThemeService; + + // Act + await InvokeAsync("SynchronizeBundledThemesIfNeededAsync", CancellationToken.None); + + // Assert + mockThemeService.DidNotReceive().GetBundledThemeArchivePaths(); + } + + [Fact] + public async Task SynchronizeBundledThemesIfNeededAsync_WhenNoRepairThemesJobExists_ShouldSynchronizeTheBundledThemes() + { + // Arrange + _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(Array.Empty()); + IThemeService mockThemeService = Substitute.For(); + mockThemeService.GetBundledThemeArchivePaths().Returns([]); + IThemeRepository mockThemeRepository = Substitute.For(); + mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From(Enumerable.Empty())); + _mockUnitOfWork.ThemeRepository.Returns(mockThemeRepository); + _services[typeof(IThemeService)] = mockThemeService; + + // Act + await InvokeAsync("SynchronizeBundledThemesIfNeededAsync", CancellationToken.None); + + // Assert + mockThemeService.Received(1).GetBundledThemeArchivePaths(); + await mockThemeRepository.Received(1).GetAllAsync(Arg.Any()); + } + + [Fact] + public async Task SynchronizeBundledThemesIfNeededAsync_WhenReadingTheScheduledJobsThrows_ShouldSwallowTheException() + { + // Arrange + Task>> faultedRead = Task.FromException>>(new InvalidOperationException("The database is unavailable.")); + _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(faultedRead); + IThemeService mockThemeService = Substitute.For(); + _services[typeof(IThemeService)] = mockThemeService; + + // Act + await InvokeAsync("SynchronizeBundledThemesIfNeededAsync", CancellationToken.None); + + // Assert + mockThemeService.DidNotReceive().GetBundledThemeArchivePaths(); + } + + [Fact] + public async Task SynchronizeBundledThemesIfNeededAsync_WhenTheThemeServiceCannotBeResolved_ShouldSwallowTheException() + { + // Arrange + _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(Array.Empty()); + // The theme service is intentionally not registered in the services of the scope. + + // Act + await InvokeAsync("SynchronizeBundledThemesIfNeededAsync", CancellationToken.None); + + // Assert + // The generic exception handler swallowed the resolution failure, so the scheduled jobs were still read. + await _mockScheduledJobRepository.Received(1).GetActiveOrRunningAsync(Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationIsRequested_ShouldSynchronizeThemesResumeCyclesAndStopTheBackgroundService() + { + // Arrange + _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(Array.Empty()); + IThemeService mockThemeService = Substitute.For(); + mockThemeService.GetBundledThemeArchivePaths().Returns([]); + IThemeRepository mockThemeRepository = Substitute.For(); + mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From(Enumerable.Empty())); + _mockUnitOfWork.ThemeRepository.Returns(mockThemeRepository); + _services[typeof(IThemeService)] = mockThemeService; + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + await InvokeAsync("ExecuteAsync", cancellationTokenSource.Token); + + // Assert + mockThemeService.Received(1).GetBundledThemeArchivePaths(); + await _mockScheduledJobRepository.Received(2).GetActiveOrRunningAsync(Arg.Any()); + } + + [Fact] + public async Task RunCycleWorkerAsync_WhenTheScheduleCannotBeLoaded_ShouldEndTheCycle() + { + // Arrange + ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); + Error error = Error.Failure("ScheduledJobs.NotFound", "Failed to read the scheduled job"); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(error); + + // Act + await InvokeAsync("RunCycleWorkerAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockTaskExecutor.DidNotReceive().ExecutePayloadAsync(Arg.Any(), Arg.Any()); + Assert.False(_runtimeRegistry.HasActiveCycle(scheduledJobId)); + } + + [Fact] + public async Task ExecuteScheduledJobRunAsync_WhenCancelledBeforeItStarts_ShouldNotRunTheTask() + { + // Arrange + ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + await InvokeAsync("ExecuteScheduledJobRunAsync", scheduledJobId, false, cancellationTokenSource.Token); + + // Assert + await _mockTaskExecutor.DidNotReceive().ExecutePayloadAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ExecuteScheduledJobRunAsync_WhenTheJobCannotBeRead_ShouldReturnWithoutRunningTheTask() + { + // Arrange + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + Error error = Error.Failure("ScheduledJobs.NotFound", "Failed to read the scheduled job"); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(error); + + // Act + await InvokeAsync("ExecuteScheduledJobRunAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockTaskExecutor.DidNotReceive().ExecutePayloadAsync(Arg.Any(), Arg.Any()); + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ExecuteScheduledJobRunAsync_WhenTheJobCannotBeConvertedToDomain_ShouldReturnWithoutRunningTheTask() + { + // Arrange + // An interval schedule whose interval is not positive cannot be converted to its domain object. + ScheduledJobEntity invalidJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 0); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(invalidJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(invalidJob); + + // Act + await InvokeAsync("ExecuteScheduledJobRunAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockTaskExecutor.DidNotReceive().ExecutePayloadAsync(Arg.Any(), Arg.Any()); + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ExecuteScheduledJobRunAsync_WhenTheTokenIsCancelledAfterTheExecutionStarted_ShouldNotRunTheTaskPayload() + { + // Arrange + ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + using CancellationTokenSource cancellationTokenSource = new(); + _mockDomainEventPublisher.When(publisher => publisher.PublishAsync(Arg.Any(), Arg.Any())) + .Do(_ => cancellationTokenSource.Cancel()); + + // Act + await InvokeAsync("ExecuteScheduledJobRunAsync", scheduledJobId, false, cancellationTokenSource.Token); + + // Assert + await _mockTaskExecutor.DidNotReceive().ExecutePayloadAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ExecuteScheduledJobRunAsync_WhenTheTaskPayloadFails_ShouldLogTheFailureAndStillCompleteTheExecution() + { + // Arrange + ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60)); + _mockTaskExecutor.ExecutePayloadAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Task.Failed", "The task of the scheduled job failed.")); + + // Act + await InvokeAsync("ExecuteScheduledJobRunAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockTaskExecutor.Received(1).ExecutePayloadAsync(Arg.Any(), Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => !domainEvent.IsCycleRun), Arg.Any()); + } + + [Fact] + public async Task ExecuteScheduledJobRunAsync_WhenTheTaskPayloadThrows_ShouldLogTheExceptionAndStillCompleteTheExecution() + { + // Arrange + ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60)); + _mockTaskExecutor.ExecutePayloadAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromException>(new InvalidOperationException("The task threw."))); + + // Act + await InvokeAsync("ExecuteScheduledJobRunAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => !domainEvent.IsCycleRun), Arg.Any()); + } + + [Fact] + public async Task ExecuteScheduledJobRunAsync_WhenTheTaskPayloadIsCancelled_ShouldReturnWithoutCompletingTheExecution() + { + // Arrange + ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + _mockTaskExecutor.ExecutePayloadAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromException>(new OperationCanceledException())); + + // Act + await InvokeAsync("ExecuteScheduledJobRunAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Is(_ => true), Arg.Any()); + } + + [Fact] + public async Task ExecuteScheduledJobRunAsync_WhenTheTokenIsCancelledAfterThePayloadRan_ShouldNotCompleteTheExecution() + { + // Arrange + ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + using CancellationTokenSource cancellationTokenSource = new(); + _mockTaskExecutor.When(executor => executor.ExecutePayloadAsync(Arg.Any(), Arg.Any())) + .Do(_ => cancellationTokenSource.Cancel()); + _mockTaskExecutor.ExecutePayloadAsync(Arg.Any(), Arg.Any()).Returns(Result.Success); + + // Act + await InvokeAsync("ExecuteScheduledJobRunAsync", scheduledJobId, false, cancellationTokenSource.Token); + + // Assert + await _mockTaskExecutor.Received(1).ExecutePayloadAsync(Arg.Any(), Arg.Any()); + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Is(_ => true), Arg.Any()); + } + + [Fact] + public async Task RunScheduledJobAsync_WhenAnotherExecutionIsAlreadyRunning_ShouldSkipTheExecution() + { + // Arrange + ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + Assert.True(_runtimeRegistry.TryAcquireRunSlot(scheduledJobId)); + + // Act + await InvokeAsync("RunScheduledJobAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockTaskExecutor.DidNotReceive().ExecutePayloadAsync(Arg.Any(), Arg.Any()); + Assert.False(_runtimeRegistry.TryAcquireRunSlot(scheduledJobId)); + _runtimeRegistry.ReleaseRunSlot(scheduledJobId); + } + + [Fact] + public async Task RunScheduledJobAsync_WhenTheStartedEventPublishingIsCancelled_ShouldReleaseTheRunSlot() + { + // Arrange + ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob, runningJob); + _mockDomainEventPublisher.When(publisher => publisher.PublishAsync(Arg.Any(), Arg.Any())) + .Do(_ => throw new OperationCanceledException()); + + // Act + await InvokeAsync("RunScheduledJobAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + Assert.True(_runtimeRegistry.TryAcquireRunSlot(scheduledJobId)); + _runtimeRegistry.ReleaseRunSlot(scheduledJobId); + } + + [Fact] + public async Task CompleteExecutionAsync_WhenTheJobCannotBeReloaded_ShouldNotCompleteTheExecution() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(Error.Failure("ScheduledJobs.NotFound", "Failed to read the scheduled job")); + ScheduledJob scheduledJob = _scheduledJobFixture.Create(id: runningJob.Id, status: ScheduledJobStatus.Added); + scheduledJob.MarkExecutionStarted(isCycleRun: false); + + // Act + await InvokeAsync("CompleteExecutionAsync", scheduledJob, _mockUnitOfWork, _mockDomainEventPublisher, false, CancellationToken.None); + + // Assert + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Is(_ => true), Arg.Any()); + } + + [Fact] + public async Task CompleteExecutionAsync_WhenTheJobIsNotRunningAnymore_ShouldNotCompleteTheExecution() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + ScheduledJob scheduledJob = _scheduledJobFixture.Create(id: runningJob.Id, status: ScheduledJobStatus.Added); + scheduledJob.MarkExecutionStarted(isCycleRun: false); + + // Act + await InvokeAsync("CompleteExecutionAsync", scheduledJob, _mockUnitOfWork, _mockDomainEventPublisher, false, CancellationToken.None); + + // Assert + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Is(_ => true), Arg.Any()); + } + + [Fact] + public async Task CompleteExecutionAsync_WhenTheExecutionCannotBeMarkedCompleted_ShouldNotPublishTheCompletionEvent() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + // The domain scheduled job was never marked as started, so its execution cannot be marked as completed. + ScheduledJob scheduledJob = _scheduledJobFixture.Create(id: runningJob.Id, status: ScheduledJobStatus.Active); + + // Act + await InvokeAsync("CompleteExecutionAsync", scheduledJob, _mockUnitOfWork, _mockDomainEventPublisher, false, CancellationToken.None); + + // Assert + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Is(_ => true), Arg.Any()); + } + + [Fact] + public async Task CompleteExecutionAsync_WhenPublishingTheCompletionEventFails_ShouldReconcileTheInterruptedRun() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); + _mockDomainEventPublisher.When(publisher => publisher.PublishAsync(Arg.Is(_ => true), Arg.Any())) + .Do(_ => throw new InvalidOperationException("publish failed")); + ScheduledJob scheduledJob = _scheduledJobFixture.Create(id: runningJob.Id, status: ScheduledJobStatus.Added); + scheduledJob.MarkExecutionStarted(isCycleRun: false); + + // Act + await InvokeAsync("CompleteExecutionAsync", scheduledJob, _mockUnitOfWork, _mockDomainEventPublisher, false, CancellationToken.None); + + // Assert + await _mockScheduledJobRepository.Received(1).UpdateAsync(Arg.Is(entity => entity.Status == ScheduledJobStatus.Active), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task ReconcileInterruptedRunAsync_WhenTheJobCannotBeRead_ShouldReturnAdded() + { + // Arrange + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("ScheduledJobs.NotFound", "Failed to read the scheduled job")); + + // Act + ScheduledJobStatus result = await InvokeAsync("ReconcileInterruptedRunAsync", scheduledJobId, CancellationToken.None); + + // Assert + Assert.Equal(ScheduledJobStatus.Added, result); + } + + [Fact] + public async Task ReconcileInterruptedRunAsync_WhenTheOpenExecutionCannotBeRead_ShouldReturnAdded() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("ScheduledJobExecutions.NotFound", "Failed to read the open execution")); + + // Act + ScheduledJobStatus result = await InvokeAsync("ReconcileInterruptedRunAsync", scheduledJobId, CancellationToken.None); + + // Assert + Assert.Equal(ScheduledJobStatus.Added, result); + await _mockScheduledJobRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task CompleteExecutionAsync_WhenPublishingTheCompletionEventIsCancelled_ShouldSwallowTheCancellation() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockDomainEventPublisher.When(publisher => publisher.PublishAsync(Arg.Is(_ => true), Arg.Any())) + .Do(_ => throw new OperationCanceledException()); + ScheduledJob scheduledJob = _scheduledJobFixture.Create(id: runningJob.Id, status: ScheduledJobStatus.Added); + scheduledJob.MarkExecutionStarted(isCycleRun: false); + + // Act + await InvokeAsync("CompleteExecutionAsync", scheduledJob, _mockUnitOfWork, _mockDomainEventPublisher, false, CancellationToken.None); + + // Assert + // A cancelled completion is a normal shutdown outcome, so no reconciliation is started. + await _mockScheduledJobRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task ReconcileInterruptedRunAsync_WhenThereIsNoOpenExecution_ShouldRestoreTheJobToItsActiveState() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(null)); + + // Act + ScheduledJobStatus result = await InvokeAsync("ReconcileInterruptedRunAsync", scheduledJobId, CancellationToken.None); + + // Assert + Assert.Equal(ScheduledJobStatus.Active, result); + await _mockScheduledJobRepository.Received(1).UpdateAsync(Arg.Is(entity => entity.Status == ScheduledJobStatus.Active), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task ReconcileInterruptedRunAsync_WhenUpdatingTheScheduledJobFails_ShouldReturnAdded() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); + _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("ScheduledJobs.UpdateFailed", "Failed to update the scheduled job")); + + // Act + ScheduledJobStatus result = await InvokeAsync("ReconcileInterruptedRunAsync", scheduledJobId, CancellationToken.None); + + // Assert + Assert.Equal(ScheduledJobStatus.Added, result); + await _mockScheduledJobExecutionRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ReconcileInterruptedRunAsync_WhenClosingTheOpenExecutionFails_ShouldReturnAdded() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); + _mockScheduledJobExecutionRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("ScheduledJobExecutions.UpdateFailed", "Failed to update the execution")); + + // Act + ScheduledJobStatus result = await InvokeAsync("ReconcileInterruptedRunAsync", scheduledJobId, CancellationToken.None); + + // Assert + Assert.Equal(ScheduledJobStatus.Added, result); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task ReconcileInterruptedRunAsync_WhenSavingTheReconciliationThrows_ShouldLogAndReturnAdded() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.FromException(new InvalidOperationException("Save failed"))); + + // Act + ScheduledJobStatus result = await InvokeAsync("ReconcileInterruptedRunAsync", scheduledJobId, CancellationToken.None); + + // Assert + Assert.Equal(ScheduledJobStatus.Added, result); + } + + [Fact] + public async Task ReconcileInterruptedRunAsync_WhenSavingTheReconciliationIsCancelled_ShouldReturnAdded() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.FromException(new OperationCanceledException())); + + // Act + ScheduledJobStatus result = await InvokeAsync("ReconcileInterruptedRunAsync", scheduledJobId, CancellationToken.None); + + // Assert + Assert.Equal(ScheduledJobStatus.Added, result); + } + + [Fact] + public async Task ResumeActiveCyclesAsync_WhenTheScheduledJobsCannotBeRead_ShouldNotResumeAnyCycle() + { + // Arrange + _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()) + .Returns(Error.Failure("ScheduledJobs.NotFound", "Failed to read the scheduled jobs")); + + // Act + await InvokeAsync("ResumeActiveCyclesAsync", CancellationToken.None); + + // Assert + await _mockTaskExecutor.DidNotReceive().ExecutePayloadAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ResumeActiveCyclesAsync_WhenARunningJobWasReconciledToItsAddedState_ShouldSkipResumingItsCycle() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(new[] { runningJob }); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: false, completedOnUtc: null); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); + + // Act + await InvokeAsync("ResumeActiveCyclesAsync", CancellationToken.None); + await Task.Delay(100); + + // Assert + await _mockScheduledJobRepository.Received(1).UpdateAsync(Arg.Is(entity => entity.Status == ScheduledJobStatus.Added), Arg.Any()); + Assert.False(_runtimeRegistry.HasActiveCycle(scheduledJobId)); + } + + [Fact] + public async Task ResumeActiveCyclesAsync_WhenARunningJobWasReconciledToItsActiveState_ShouldResumeItsCycleAndFireTheTask() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.OnceAtStartup); + ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.OnceAtStartup); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(new[] { runningJob }); + // The first read reconciles the interrupted run while the job is still running; the reads made by the resumed cycle observe the reconciled active status. + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob, activeJob, activeJob); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.OnceAtStartup)); + ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); + + // Act + await InvokeAsync("ResumeActiveCyclesAsync", CancellationToken.None); + await WaitUntilAsync(() => _mockTaskExecutor.ReceivedCalls().Count() > 0); + + // Assert + await _mockTaskExecutor.Received(1).ExecutePayloadAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ResumeActiveCyclesAsync_WhenAnActiveIntervalJobExists_ShouldResumeItsCycleWithoutFiringTheTask() + { + // Arrange + ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); + _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(new[] { activeJob }); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + + // Act + await InvokeAsync("ResumeActiveCyclesAsync", CancellationToken.None); + await WaitUntilAsync(() => _runtimeRegistry.HasActiveCycle(scheduledJobId)); + await _sut.StopCycleAsync(scheduledJobId, CancellationToken.None); + await Task.Delay(50); + + // Assert + await _mockTaskExecutor.DidNotReceive().ExecutePayloadAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task RunCycleWorkerAsync_WhenTheTimerTicks_ShouldRunTheTaskAfterEachTickAndEndTheCycle() + { + // Arrange + ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + RegisterDateTimeProvider(); + IScheduledJobCycleTicker mockCycleTicker = Substitute.For(); + mockCycleTicker.WaitForNextTickAsync(Arg.Any()) + .Returns(new ValueTask(true), new ValueTask(true), new ValueTask(false)); + ScheduledJobSchedulerJob schedulerJob = CreateScheduledJobSchedulerJob(_ => mockCycleTicker); + + // Act + await InvokeOnAsync(schedulerJob, "RunCycleWorkerAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockTaskExecutor.Received(2).ExecutePayloadAsync(Arg.Any(), Arg.Any()); + await _mockDomainEventPublisher.Received(2).PublishAsync(Arg.Is(domainEvent => domainEvent.IsCycleRun), Arg.Any()); + Assert.False(_runtimeRegistry.HasActiveCycle(scheduledJobId)); + } + + [Fact] + public async Task RunCycleWorkerAsync_WhenTheTimerTicksForADailySchedule_ShouldRecalculateThePeriodAfterEveryRun() + { + // Arrange + ScheduledJobEntity dailyJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.DailyAtHourAndMinute, hour: 10, minute: 30); + ScheduledJobEntity runningDailyJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.DailyAtHourAndMinute, hour: 10, minute: 30); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(dailyJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(dailyJob); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(runningDailyJob); + RegisterDateTimeProvider(); + IScheduledJobCycleTicker mockCycleTicker = Substitute.For(); + mockCycleTicker.WaitForNextTickAsync(Arg.Any()) + .Returns(new ValueTask(true), new ValueTask(false)); + ScheduledJobSchedulerJob schedulerJob = CreateScheduledJobSchedulerJob(_ => mockCycleTicker); + + // Act + await InvokeOnAsync(schedulerJob, "RunCycleWorkerAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockTaskExecutor.Received(1).ExecutePayloadAsync(Arg.Any(), Arg.Any()); + mockCycleTicker.Received(1).Period = Arg.Any(); + Assert.False(_runtimeRegistry.HasActiveCycle(scheduledJobId)); + } + + [Fact] + public async Task RunCycleWorkerAsync_WhenTheCycleIsStoppedDuringARun_ShouldEndTheCycleOnTheNextTick() + { + // Arrange + ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + RegisterDateTimeProvider(); + _mockTaskExecutor.ExecutePayloadAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Success) + .AndDoes(_ => _runtimeRegistry.StopCycle(scheduledJobId)); + IScheduledJobCycleTicker mockCycleTicker = Substitute.For(); + mockCycleTicker.WaitForNextTickAsync(Arg.Any()) + .Returns(new ValueTask(true), new ValueTask(true), new ValueTask(false)); + ScheduledJobSchedulerJob schedulerJob = CreateScheduledJobSchedulerJob(_ => mockCycleTicker); + + // Act + await InvokeOnAsync(schedulerJob, "RunCycleWorkerAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockTaskExecutor.Received(1).ExecutePayloadAsync(Arg.Any(), Arg.Any()); + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Is(_ => true), Arg.Any()); + Assert.False(_runtimeRegistry.HasActiveCycle(scheduledJobId)); + } + + [Fact] + public async Task RunCycleWorkerAsync_WhenTheCycleTokenIsCancelled_ShouldSwallowTheCancellationAndEndTheCycle() + { + // Arrange + ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + RegisterDateTimeProvider(); + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + await InvokeAsync("RunCycleWorkerAsync", scheduledJobId, false, cancellationTokenSource.Token); + + // Assert + await _mockTaskExecutor.DidNotReceive().ExecutePayloadAsync(Arg.Any(), Arg.Any()); + Assert.False(_runtimeRegistry.HasActiveCycle(scheduledJobId)); + } + + [Fact] + public async Task RunCycleWorkerAsync_WhenWaitingForTheNextTickThrows_ShouldLogTheErrorAndEndTheCycle() + { + // Arrange + ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + RegisterDateTimeProvider(); + IScheduledJobCycleTicker mockCycleTicker = Substitute.For(); + mockCycleTicker.WaitForNextTickAsync(Arg.Any()) + .Returns(new ValueTask(Task.FromException(new InvalidOperationException("The ticker failed.")))); + ScheduledJobSchedulerJob schedulerJob = CreateScheduledJobSchedulerJob(_ => mockCycleTicker); + + // Act + await InvokeOnAsync(schedulerJob, "RunCycleWorkerAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockTaskExecutor.DidNotReceive().ExecutePayloadAsync(Arg.Any(), Arg.Any()); + Assert.False(_runtimeRegistry.HasActiveCycle(scheduledJobId)); + } + + [Fact] + public async Task CalculateDelayAsync_WhenCalledWithAnIntervalSchedule_ShouldReturnTheIntervalDelay() + { + // Arrange + IntervalSchedule intervalSchedule = _intervalScheduleFixture.Create(intervalMinutes: 30); + IDateTimeProvider mockDateTimeProvider = Substitute.For(); + mockDateTimeProvider.UtcNow.Returns(new DateTime(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc)); + _services[typeof(IDateTimeProvider)] = mockDateTimeProvider; + + // Act + TimeSpan result = await InvokeAsync("CalculateDelayAsync", intervalSchedule); + + // Assert + Assert.Equal(TimeSpan.FromMinutes(30), result); + } + + [Fact] + public async Task GetScheduleAsync_WhenTheScheduledJobCannotBeConvertedToDomain_ShouldReturnNull() + { + // Arrange + // An interval schedule whose interval is not positive cannot be converted to its domain object. + ScheduledJobEntity invalidJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 0); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(invalidJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(invalidJob); + + // Act + Schedule? result = await InvokeAsync("GetScheduleAsync", scheduledJobId, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + /// + /// Registers a date time provider that returns a fixed UTC time in the services of the mocked scope. + /// + private void RegisterDateTimeProvider() + { + IDateTimeProvider mockDateTimeProvider = Substitute.For(); + mockDateTimeProvider.UtcNow.Returns(new DateTime(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc)); + _services[typeof(IDateTimeProvider)] = mockDateTimeProvider; + } + + /// + /// Creates a new instance of the class whose cycle cadence is driven by the tickers created by . + /// + /// The factory that creates the ticker driving the cadence of an execution cycle. + /// The created scheduled job scheduler. + private ScheduledJobSchedulerJob CreateScheduledJobSchedulerJob(Func cycleTickerFactory) + { + ILogger logger = Substitute.For>(); + return new ScheduledJobSchedulerJob(_runtimeRegistry, logger, _mockServiceScopeFactory, cycleTickerFactory); + } + + /// + /// Invokes the private method named on and awaits its returned task. + /// + /// The scheduled job scheduler on which the private method is invoked. + /// The name of the private method to invoke. + /// The arguments of the method. + private static async Task InvokeOnAsync(ScheduledJobSchedulerJob schedulerJob, string methodName, params object?[] args) + { + Task task = (Task)GetPrivateMethod(methodName).Invoke(schedulerJob, args)!; + await task.ConfigureAwait(false); + } + + /// + /// Invokes the private method named and awaits its returned task. + /// + /// The name of the private method to invoke. + /// The arguments of the method. + private async Task InvokeAsync(string methodName, params object?[] args) + { + Task task = (Task)GetPrivateMethod(methodName).Invoke(_sut, args)!; + await task.ConfigureAwait(false); + } + + /// + /// Invokes the private method named and awaits its returned task of type . + /// + /// The name of the private method to invoke. + /// The arguments of the method. + /// The type of the value the task returns. + /// The value returned by the method. + private async Task InvokeAsync(string methodName, params object?[] args) + { + Task task = (Task)GetPrivateMethod(methodName).Invoke(_sut, args)!; + return await task.ConfigureAwait(false); + } + + /// + /// Gets the private instance method named . + /// + /// The name of the method. + /// The reflected method. + private static MethodInfo GetPrivateMethod(string methodName) + { + return typeof(ScheduledJobSchedulerJob).GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException($"The method '{methodName}' was not found on the scheduled job scheduler."); + } + + /// + /// Waits until the provided condition is met, or the timeout elapses. + /// + /// The condition to wait for. + /// A task that represents the asynchronous operation. + private static async Task WaitUntilAsync(Func condition) + { + int remainingAttempts = 200; + while (!condition() && remainingAttempts > 0) + { + remainingAttempts--; + await Task.Delay(10); + } + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledTaskExecutorFactoryTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledTaskExecutorFactoryTests.cs new file mode 100644 index 00000000..075bace8 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledTaskExecutorFactoryTests.cs @@ -0,0 +1,108 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Domain.Common.Events; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using Lumina.Infrastructure.Core.Scheduling.Execution; +using Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Execution; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledTaskExecutorFactoryTests +{ + private readonly IServiceProvider _mockServiceProvider; + private readonly MediaLibraryScanTaskExecutor _mockMediaLibraryScanTaskExecutor; + private readonly TemporaryFilesCleanupTaskExecutor _mockTemporaryFilesCleanupTaskExecutor; + private readonly RepairThemesTaskExecutor _mockRepairThemesTaskExecutor; + private readonly CleanScheduledJobExecutionHistoryTaskExecutor _mockCleanScheduledJobExecutionHistoryTaskExecutor; + private readonly ScheduledTaskExecutorFactory _sut; + + /// + /// Initializes a new instance of the class. + /// + public ScheduledTaskExecutorFactoryTests() + { + _mockServiceProvider = Substitute.For(); + _mockMediaLibraryScanTaskExecutor = Substitute.For( + Substitute.For(), + Substitute.For>(), + Substitute.For()); + _mockTemporaryFilesCleanupTaskExecutor = Substitute.For( + Substitute.For>()); + _mockRepairThemesTaskExecutor = Substitute.For( + Substitute.For(), + Substitute.For>(), + Substitute.For()); + _mockCleanScheduledJobExecutionHistoryTaskExecutor = Substitute.For( + Substitute.For(), + Substitute.For>(), + Substitute.For()); + + _mockServiceProvider.GetService(typeof(MediaLibraryScanTaskExecutor)).Returns(_mockMediaLibraryScanTaskExecutor); + _mockServiceProvider.GetService(typeof(TemporaryFilesCleanupTaskExecutor)).Returns(_mockTemporaryFilesCleanupTaskExecutor); + _mockServiceProvider.GetService(typeof(RepairThemesTaskExecutor)).Returns(_mockRepairThemesTaskExecutor); + _mockServiceProvider.GetService(typeof(CleanScheduledJobExecutionHistoryTaskExecutor)).Returns(_mockCleanScheduledJobExecutionHistoryTaskExecutor); + + _sut = new ScheduledTaskExecutorFactory(_mockServiceProvider); + } + + [Fact] + public void CreateExecutor_WhenTaskTypeIsScanMediaLibraries_ShouldReturnMediaLibraryScanTaskExecutor() + { + // Act + IScheduledTaskExecutor result = _sut.CreateExecutor(ScheduledTaskType.ScanMediaLibraries); + + // Assert + Assert.Same(_mockMediaLibraryScanTaskExecutor, result); + } + + [Fact] + public void CreateExecutor_WhenTaskTypeIsCleanTemporaryFiles_ShouldReturnTemporaryFilesCleanupTaskExecutor() + { + // Act + IScheduledTaskExecutor result = _sut.CreateExecutor(ScheduledTaskType.CleanTemporaryFiles); + + // Assert + Assert.Same(_mockTemporaryFilesCleanupTaskExecutor, result); + } + + [Fact] + public void CreateExecutor_WhenTaskTypeIsRepairThemes_ShouldReturnRepairThemesTaskExecutor() + { + // Act + IScheduledTaskExecutor result = _sut.CreateExecutor(ScheduledTaskType.RepairThemes); + + // Assert + Assert.Same(_mockRepairThemesTaskExecutor, result); + } + + [Fact] + public void CreateExecutor_WhenTaskTypeIsCleanScheduledJobExecutionHistory_ShouldReturnCleanScheduledJobExecutionHistoryTaskExecutor() + { + // Act + IScheduledTaskExecutor result = _sut.CreateExecutor(ScheduledTaskType.CleanScheduledJobExecutionHistory); + + // Assert + Assert.Same(_mockCleanScheduledJobExecutionHistoryTaskExecutor, result); + } + + [Fact] + public void CreateExecutor_WhenTaskTypeIsUnsupported_ShouldThrowArgumentException() + { + // Act + ArgumentException exception = Assert.Throws(() => _sut.CreateExecutor((ScheduledTaskType)999)); + + // Assert + Assert.Contains("Unsupported task type", exception.Message); + Assert.Equal("taskType", exception.ParamName); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/CleanScheduledJobExecutionHistoryTaskExecutorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/CleanScheduledJobExecutionHistoryTaskExecutorTests.cs new file mode 100644 index 00000000..0cbb40d1 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/CleanScheduledJobExecutionHistoryTaskExecutorTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Execution.TaskExecutors; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CleanScheduledJobExecutionHistoryTaskExecutorTests +{ + private readonly IDateTimeProvider _mockDateTimeProvider; + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IScheduledJobExecutionRepository _mockScheduledJobExecutionRepository; + private readonly CleanScheduledJobExecutionHistoryTaskExecutor _sut; + private readonly ScheduledJobFixture _scheduledJobFixture = new(); + private readonly DateTime _fixedUtcNow = DateTime.UtcNow; + + /// + /// Initializes a new instance of the class. + /// + public CleanScheduledJobExecutionHistoryTaskExecutorTests() + { + _mockDateTimeProvider = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockScheduledJobExecutionRepository = Substitute.For(); + _mockDateTimeProvider.UtcNow.Returns(_fixedUtcNow); + _mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository); + ILogger logger = Substitute.For>(); + _sut = new CleanScheduledJobExecutionHistoryTaskExecutor(_mockDateTimeProvider, logger, _mockUnitOfWork); + } + + [Fact] + public async Task ExecutePayloadAsync_WhenCalled_ShouldDeleteTheExecutionsOlderThanAMonth() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.CleanScheduledJobExecutionHistory); + _mockScheduledJobExecutionRepository.DeleteOlderThanAsync(Arg.Any(), Arg.Any()).Returns(Result.Success); + DateTime expectedCutoff = _fixedUtcNow.AddMonths(-1); + + // Act + Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockScheduledJobExecutionRepository.Received(1).DeleteOlderThanAsync(Arg.Is(cutoff => cutoff == expectedCutoff), Arg.Any()); + } + + [Fact] + public async Task ExecutePayloadAsync_WhenTheDeletionFails_ShouldReturnTheError() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.CleanScheduledJobExecutionHistory); + Error expectedError = Error.Failure("Database.Error", "Failed to delete the old executions"); + _mockScheduledJobExecutionRepository.DeleteOlderThanAsync(Arg.Any(), Arg.Any()).Returns(expectedError); + + // Act + Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(expectedError, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutorTests.cs new file mode 100644 index 00000000..ed5ca893 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutorTests.cs @@ -0,0 +1,172 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Execution.TaskExecutors; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScanTaskExecutorTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IDomainEventPublisher _mockDomainEventPublisher; + private readonly MediaLibraryScanTaskExecutor _sut; + private readonly ScheduledJobFixture _scheduledJobFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public MediaLibraryScanTaskExecutorTests() + { + _mockUnitOfWork = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any()) + .Returns(Result.From>([])); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockDomainEventPublisher = Substitute.For(); + _sut = new MediaLibraryScanTaskExecutor(_mockDomainEventPublisher, Substitute.For>(), _mockUnitOfWork); + } + + [Fact] + public async Task ExecutePayloadAsync_WhenNoLibrariesAreEnabled_ShouldReturnSuccessWithoutPublishingEvents() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(); + + // Act + Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Success, result.Value); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ExecutePayloadAsync_WhenGetAllEnabledAndUnlockedLibrariesFails_ShouldReturnError() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to get the enabled libraries"); + _mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task ExecutePayloadAsync_WhenGetPastMonthScansFails_ShouldReturnError() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(); + LibraryEntity library = _libraryEntityFixture.Create(); + _mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any()) + .Returns(Result.From>([library])); + Error error = Error.Failure("Database.Error", "Failed to get the past month scans"); + _mockUnitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + } + + [Fact] + public async Task ExecutePayloadAsync_WhenALibraryIsAlreadyBeingScanned_ShouldSkipThatLibrary() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(); + LibraryEntity library = _libraryEntityFixture.Create(); + _mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any()) + .Returns(Result.From>([library])); + LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(libraryId: library.Id, status: LibraryScanJobStatus.Running); + _mockUnitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([runningScan])); + + // Act + Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ExecutePayloadAsync_WhenAQueuedScanIsInserted_ShouldPublishItsDomainEvents() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(); + LibraryEntity library = _libraryEntityFixture.Create(); + _mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any()) + .Returns(Result.From>([library])); + _mockUnitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + _mockUnitOfWork.LibraryScanRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + + // Act + Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockUnitOfWork.LibraryScanRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ExecutePayloadAsync_WhenInsertingTheQueuedScanFails_ShouldReturnError() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(); + LibraryEntity library = _libraryEntityFixture.Create(); + _mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any()) + .Returns(Result.From>([library])); + _mockUnitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + Error error = Error.Failure("Database.Error", "Failed to insert the scan"); + _mockUnitOfWork.LibraryScanRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/RepairThemesTaskExecutorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/RepairThemesTaskExecutorTests.cs new file mode 100644 index 00000000..fc7632b1 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/RepairThemesTaskExecutorTests.cs @@ -0,0 +1,119 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Themes; +using Lumina.Application.Common.DataAccess.Repositories.Themes; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Models.DTO.Themes; +using Lumina.Application.Common.Infrastructure.Themes; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Execution.TaskExecutors; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RepairThemesTaskExecutorTests +{ + private readonly IThemeService _mockThemeService; + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IThemeRepository _mockThemeRepository; + private readonly RepairThemesTaskExecutor _sut; + private readonly ScheduledJobFixture _scheduledJobFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public RepairThemesTaskExecutorTests() + { + _mockThemeService = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockThemeRepository = Substitute.For(); + _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + ILogger logger = Substitute.For>(); + _sut = new RepairThemesTaskExecutor(_mockThemeService, logger, _mockUnitOfWork); + } + + [Fact] + public async Task ExecutePayloadAsync_WhenCalled_ShouldSynchronizeTheThemes() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.RepairThemes); + _mockThemeService.GetBundledThemeArchivePaths().Returns([]); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From(Enumerable.Empty())); + + // Act + Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockThemeRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task ExecutePayloadAsync_WhenABundledThemeArchiveCannotBeRead_ShouldStillSucceed() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.RepairThemes); + _mockThemeService.GetBundledThemeArchivePaths().Returns(["missing.zip"]); + _mockThemeService.ReadManifestFromArchiveAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Theme.Manifest", "Failed to read the theme manifest")); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From(Enumerable.Empty())); + + // Act + Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockThemeRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task ExecutePayloadAsync_WhenTheSynchronizationThrows_ShouldReturnFailure() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.RepairThemes); + _mockThemeRepository.GetAllAsync(Arg.Any()) + .Returns(Task.FromException>>(new InvalidOperationException("The database is unavailable."))); + + // Act + Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(nameof(RepairThemesTaskExecutor), result.FirstError.Description); + } + + [Fact] + public async Task ExecutePayloadAsync_WhenTheSynchronizationIsCancelled_ShouldRethrowTheCancellation() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.RepairThemes); + _mockThemeRepository.GetAllAsync(Arg.Any()) + .Returns(Task.FromException>>(new OperationCanceledException())); + + // Act + async Task Act() + { + await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/TemporaryFilesCleanupTaskExecutorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/TemporaryFilesCleanupTaskExecutorTests.cs new file mode 100644 index 00000000..ad42bdd4 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/TemporaryFilesCleanupTaskExecutorTests.cs @@ -0,0 +1,94 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Execution.TaskExecutors; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TemporaryFilesCleanupTaskExecutorTests +{ + private readonly TemporaryFilesCleanupTaskExecutor _sut; + private readonly ScheduledJobFixture _scheduledJobFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public TemporaryFilesCleanupTaskExecutorTests() + { + ILogger logger = Substitute.For>(); + _sut = new TemporaryFilesCleanupTaskExecutor(logger); + } + + [Fact] + public async Task ExecutePayloadAsync_WhenTemporaryDirectoryExists_ShouldEmptyItAndReturnSuccess() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(); + string temporaryDirectory = Path.Combine(AppContext.BaseDirectory, "reading-cache"); + Directory.CreateDirectory(Path.Combine(temporaryDirectory, "subdirectory")); + File.WriteAllText(Path.Combine(temporaryDirectory, "subdirectory", "file.txt"), "content"); + + // Act + Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Success, result.Value); + Assert.True(Directory.Exists(temporaryDirectory)); + Assert.Empty(Directory.GetFileSystemEntries(temporaryDirectory)); + } + + [Fact] + public async Task ExecutePayloadAsync_WhenTemporaryDirectoryDoesNotExist_ShouldRecreateItAndReturnSuccess() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(); + string temporaryDirectory = Path.Combine(AppContext.BaseDirectory, "reading-cache"); + if (Directory.Exists(temporaryDirectory)) + Directory.Delete(temporaryDirectory, recursive: true); + + // Act + Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Success, result.Value); + Assert.True(Directory.Exists(temporaryDirectory)); + } + + [Fact] + public async Task ExecutePayloadAsync_WhenDeletingTheDirectoryFails_ShouldReturnError() + { + // On non Windows platforms deleting a file that is locked open succeeds, so the failure path can only be forced on Windows. + if (!OperatingSystem.IsWindows()) + return; + + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(); + string temporaryDirectory = Path.Combine(AppContext.BaseDirectory, "reading-cache"); + Directory.CreateDirectory(temporaryDirectory); + string lockedFile = Path.Combine(temporaryDirectory, "locked.txt"); + File.WriteAllText(lockedFile, "content"); + // Lock the file with an exclusive handle so the recursive delete fails. + using FileStream lockStream = new(lockedFile, FileMode.Open, FileAccess.Read, FileShare.None); + + // Act + Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Notifications/ScheduledJobNotifierTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Notifications/ScheduledJobNotifierTests.cs new file mode 100644 index 00000000..df53a5d2 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Notifications/ScheduledJobNotifierTests.cs @@ -0,0 +1,82 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Responses.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Infrastructure.Core.Scheduling.Notifications; +using Microsoft.AspNetCore.SignalR; +using NSubstitute; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Notifications; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobNotifierTests +{ + private readonly IHubContext _mockHubContext; + private readonly IHubClients _mockHubClients; + private readonly IScheduledJobsClient _mockClient; + private readonly ScheduledJobNotifier _sut; + private readonly ScheduledJobResponseFixture _scheduledJobResponseFixture = new(); + private readonly ScheduledJobExecutionResponseFixture _scheduledJobExecutionResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ScheduledJobNotifierTests() + { + _mockClient = Substitute.For(); + _mockHubClients = Substitute.For>(); + _mockHubClients.Group(ScheduledJobsHub.ADMINISTRATORS_GROUP).Returns(_mockClient); + _mockHubContext = Substitute.For>(); + _mockHubContext.Clients.Returns(_mockHubClients); + _sut = new ScheduledJobNotifier(_mockHubContext); + } + + [Fact] + public async Task SendScheduledJobsAsync_WhenCalled_ShouldSendTheScheduledJobsToTheAdministratorGroup() + { + // Arrange + IReadOnlyList scheduledJobs = _scheduledJobResponseFixture.CreateMany(2); + + // Act + await _sut.SendScheduledJobsAsync(scheduledJobs, CancellationToken.None); + + // Assert + await _mockClient.Received(1).ReceiveScheduledJobsAsync(scheduledJobs); + _mockHubClients.Received(1).Group(ScheduledJobsHub.ADMINISTRATORS_GROUP); + } + + [Fact] + public async Task SendScheduledJobExecutionStartedAsync_WhenCalled_ShouldSendTheExecutionToTheAdministratorGroup() + { + // Arrange + ScheduledJobExecutionResponse execution = _scheduledJobExecutionResponseFixture.Create(); + + // Act + await _sut.SendScheduledJobExecutionStartedAsync(execution, CancellationToken.None); + + // Assert + await _mockClient.Received(1).ScheduledJobExecutionStartedAsync(execution); + _mockHubClients.Received(1).Group(ScheduledJobsHub.ADMINISTRATORS_GROUP); + } + + [Fact] + public async Task SendScheduledJobExecutionCompletedAsync_WhenCalled_ShouldSendTheExecutionToTheAdministratorGroup() + { + // Arrange + ScheduledJobExecutionResponse execution = _scheduledJobExecutionResponseFixture.Create(); + + // Act + await _sut.SendScheduledJobExecutionCompletedAsync(execution, CancellationToken.None); + + // Assert + await _mockClient.Received(1).ScheduledJobExecutionCompletedAsync(execution); + _mockHubClients.Received(1).Group(ScheduledJobsHub.ADMINISTRATORS_GROUP); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Notifications/ScheduledJobsHubTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Notifications/ScheduledJobsHubTests.cs new file mode 100644 index 00000000..f341d5a5 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Notifications/ScheduledJobsHubTests.cs @@ -0,0 +1,118 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Infrastructure.Core.Scheduling.Notifications; +using Microsoft.AspNetCore.SignalR; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Security.Claims; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Notifications; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobsHubTests +{ + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ScheduledJobsHub _sut; + + /// + /// Initializes a new instance of the class. + /// + public ScheduledJobsHubTests() + { + Microsoft.Extensions.DependencyInjection.IServiceScopeFactory mockScopeFactory = Substitute.For(); + Microsoft.Extensions.DependencyInjection.IServiceScope mockScope = Substitute.For(); + System.IServiceProvider mockServiceProvider = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + + mockScope.ServiceProvider.Returns(mockServiceProvider); + mockServiceProvider.GetService(typeof(IAuthorizationService)).Returns(_mockAuthorizationService); + mockScopeFactory.CreateScope().Returns(mockScope); + + _sut = new ScheduledJobsHub(mockScopeFactory); + } + + [Fact] + public async Task OnConnectedAsync_WhenUserClaimIsMissing_ShouldAbortTheConnection() + { + // Arrange + HubCallerContext context = CreateHubCallerContext(new ClaimsPrincipal(new ClaimsIdentity())); + _sut.Context = context; + + // Act + await _sut.OnConnectedAsync(); + + // Assert + context.Received(1).Abort(); + } + + [Fact] + public async Task OnConnectedAsync_WhenUserIdClaimIsNotAGuid_ShouldAbortTheConnection() + { + // Arrange + ClaimsPrincipal user = new(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, "not-a-guid")])); + HubCallerContext context = CreateHubCallerContext(user); + _sut.Context = context; + + // Act + await _sut.OnConnectedAsync(); + + // Assert + context.Received(1).Abort(); + } + + [Fact] + public async Task OnConnectedAsync_WhenUserIsNotAdministrator_ShouldAbortTheConnection() + { + // Arrange + Guid userId = Guid.NewGuid(); + ClaimsPrincipal user = new(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, userId.ToString())])); + HubCallerContext context = CreateHubCallerContext(user); + _sut.Context = context; + _mockAuthorizationService.IsInRoleAsync(userId, "Admin", System.Threading.CancellationToken.None).Returns(false); + + // Act + await _sut.OnConnectedAsync(); + + // Assert + context.Received(1).Abort(); + } + + [Fact] + public async Task OnConnectedAsync_WhenUserIsAdministrator_ShouldAddTheConnectionToTheAdministratorGroup() + { + // Arrange + Guid userId = Guid.NewGuid(); + ClaimsPrincipal user = new(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, userId.ToString())])); + HubCallerContext context = CreateHubCallerContext(user); + context.ConnectionId.Returns("connection-1"); + _sut.Context = context; + IGroupManager mockGroupManager = Substitute.For(); + _sut.Groups = mockGroupManager; + _mockAuthorizationService.IsInRoleAsync(userId, "Admin", System.Threading.CancellationToken.None).Returns(true); + + // Act + await _sut.OnConnectedAsync(); + + // Assert + context.DidNotReceive().Abort(); + await mockGroupManager.Received(1).AddToGroupAsync("connection-1", ScheduledJobsHub.ADMINISTRATORS_GROUP, System.Threading.CancellationToken.None); + } + + /// + /// Creates a mocked hub caller context carrying the provided user. + /// + /// The user of the connection. + /// The created context. + private static HubCallerContext CreateHubCallerContext(ClaimsPrincipal user) + { + HubCallerContext context = Substitute.For(); + context.User.Returns(user); + return context; + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeDetectionSyncJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeDetectionSyncJobTests.cs deleted file mode 100644 index 9c12665e..00000000 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeDetectionSyncJobTests.cs +++ /dev/null @@ -1,550 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.Themes; -using Lumina.Application.Common.DataAccess.Repositories.Themes; -using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Common.Infrastructure.Models.DTO.Themes; -using Lumina.Application.Common.Infrastructure.Themes; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; -using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Themes; -using Lumina.Domain.Common.Primitives; -using Lumina.Domain.SharedKernel.Common.Enums.Themes; -using Lumina.Infrastructure.Core.Themes; -using Lumina.Infrastructure.Fixtures.Core.Themes; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using NSubstitute; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.IO; -using System.Reflection; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Infrastructure.UnitTests.Core.Themes; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ThemeDetectionSyncJobTests : IDisposable -{ - private readonly IServiceScopeFactory _mockServiceScopeFactory; - private readonly IServiceScope _mockServiceScope; - private readonly IServiceProvider _mockServiceProvider; - private readonly IUnitOfWork _mockUnitOfWork; - private readonly IThemeRepository _mockThemeRepository; - private readonly IThemeService _mockThemeService; - private readonly ILogger _mockLogger; - private readonly ThemePackFixture _themePackFixture = new(); - private readonly ThemeEntityFixture _themeEntityFixture = new(); - private readonly ThemeManifestDtoFixture _themeManifestDtoFixture = new(); - private readonly string _testRootPath; - - /// - /// Initializes a new instance of the class. - /// - public ThemeDetectionSyncJobTests() - { - _testRootPath = Path.Combine(Path.GetTempPath(), $"lumina-theme-job-{Guid.NewGuid():N}"); - Directory.CreateDirectory(_testRootPath); - _mockServiceScopeFactory = Substitute.For(); - _mockServiceScope = Substitute.For(); - _mockServiceProvider = Substitute.For(); - _mockServiceScopeFactory.CreateAsyncScope().Returns(new AsyncServiceScope(_mockServiceScope)); - _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); - - _mockUnitOfWork = Substitute.For(); - _mockThemeRepository = Substitute.For(); - _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); - _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); - - _mockThemeService = Substitute.For(); - _mockThemeService.HasThemePack(Arg.Any()).Returns(true); - _mockLogger = Substitute.For>(); - } - - /// - /// Cleans up the temporary storage used by the tests. - /// - public void Dispose() - { - try - { - if (Directory.Exists(_testRootPath)) - Directory.Delete(_testRootPath, recursive: true); - } - catch (IOException) - { - // best effort cleanup of the per-test temp directory - } - catch (UnauthorizedAccessException) - { - // best effort cleanup of the per-test temp directory - } - } - - [Fact] - public async Task StartAsync_WhenThereAreNoBundledThemesAndNoInstalledThemes_ShouldOnlySaveChanges() - { - // Arrange - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); - _mockThemeService.GetBundledThemeArchivePaths().Returns([]); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenBundledThemeIsNotYetInstalled_ShouldInstallAndPersistTheTheme() - { - // Arrange - string archivePath = CreateBundledArchiveFile("bundled-theme"); - ThemeManifestDto manifest = _themeManifestDtoFixture.Create(id: "bundled-theme"); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); - _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); - _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(manifest); - _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).Returns(manifest); - _mockThemeRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Result.From(Result.Created)); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeService.Received(1).InstallAsync(Arg.Any(), Arg.Any()); - await _mockThemeRepository.Received(1).InsertAsync( - Arg.Is(theme => theme.ThemeId == "bundled-theme" - && theme.Name == manifest.Name - && theme.Description == manifest.Description - && theme.Version == manifest.Version - && theme.InstallSource == ThemeInstallSource.Bundled), - Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenBundledThemeIsAlreadyInstalled_ShouldSkipInstallingIt() - { - // Arrange - ThemeEntity existingTheme = _themeEntityFixture.Create(themeId: "bundled-theme", isCurrent: true, includeIsCurrent: true, installSource: ThemeInstallSource.Bundled, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([existingTheme])); - _mockThemeService.GetBundledThemeArchivePaths().Returns(["C:\\bundled\\bundled-theme.zip"]); - _mockThemeService.ReadManifestFromArchiveAsync("C:\\bundled\\bundled-theme.zip", Arg.Any()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme")); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); - await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenBundledThemeWasSoftDeletedByTheUser_ShouldNotReinstallIt() - { - // Arrange - ThemeEntity deletedTheme = _themeEntityFixture.Create(themeId: "bundled-theme", isDeleted: true, installSource: ThemeInstallSource.Bundled); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([deletedTheme])); - _mockThemeService.GetBundledThemeArchivePaths().Returns(["C:\\bundled\\bundled-theme.zip"]); - _mockThemeService.ReadManifestFromArchiveAsync("C:\\bundled\\bundled-theme.zip", Arg.Any()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme")); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); - await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenInstalledBundledThemePackIsMissingAndNotDeleted_ShouldReinstallTheFilesWithoutInsertingANewRow() - { - // Arrange - ThemeEntity existingTheme = _themeEntityFixture.Create(themeId: "bundled-theme", isCurrent: true, includeIsCurrent: true, installSource: ThemeInstallSource.Bundled, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([existingTheme])); - _mockThemeService.HasThemePack("bundled-theme").Returns(false); - string archivePath = CreateBundledArchiveFile("bundled-theme"); - ThemeManifestDto manifest = _themeManifestDtoFixture.Create(id: "bundled-theme"); - _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); - _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(manifest); - _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).Returns(manifest); - _mockThemeService.RestoreBundledThemeAsync("bundled-theme", Arg.Any()).Returns(Result.Success); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeService.Received(1).InstallAsync(Arg.Any(), Arg.Any()); - await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); - await _mockThemeRepository.DidNotReceiveWithAnyArgs().UpdateAsync(default!, Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenBundledArchiveManifestCannotBeRead_ShouldSkipTheArchive() - { - // Arrange - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); - _mockThemeService.GetBundledThemeArchivePaths().Returns(["C:\\bundled\\broken.zip"]); - _mockThemeService.ReadManifestFromArchiveAsync("C:\\bundled\\broken.zip", Arg.Any()).Returns(Error.Failure("Theme.Files", "unreadable")); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); - await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenBundledThemeInstallFails_ShouldNotPersistTheTheme() - { - // Arrange - string archivePath = CreateBundledArchiveFile("bundled-theme"); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); - _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); - _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme")); - _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).Returns(Error.Failure("Theme.Install", "install failed")); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenPersistingDetectedThemeFails_ShouldLogWarningAndContinue() - { - // Arrange - string archivePath = CreateBundledArchiveFile("bundled-theme"); - ThemeManifestDto manifest = _themeManifestDtoFixture.Create(id: "bundled-theme"); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); - _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); - _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(manifest); - _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).Returns(manifest); - _mockThemeRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Error.Failure("Database.Error", "failed to persist")); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenReadingInstalledThemesFails_ShouldReturnWithoutPersistingChanges() - { - // Arrange - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Error.Failure("Database.Error", "failed to read themes")); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - _mockThemeService.DidNotReceive().GetBundledThemeArchivePaths(); - await _mockUnitOfWork.DidNotReceiveWithAnyArgs().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenMissingBundledThemePackCanBeRestored_ShouldRestoreTheFiles() - { - // Arrange - ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "bundled-theme", isCurrent: true, includeIsCurrent: true, installSource: ThemeInstallSource.Bundled, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([brokenTheme])); - _mockThemeService.HasThemePack("bundled-theme").Returns(false); - _mockThemeService.GetBundledThemeArchivePaths().Returns([]); - _mockThemeService.RestoreBundledThemeAsync("bundled-theme", Arg.Any()).Returns(Result.Success); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeService.Received(1).RestoreBundledThemeAsync("bundled-theme", Arg.Any()); - await _mockThemeRepository.DidNotReceiveWithAnyArgs().UpdateAsync(default!, Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenRestoringBundledThemeThrows_ShouldNotCrashTheJob() - { - // Arrange - ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "bundled-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([brokenTheme])); - _mockThemeService.HasThemePack("bundled-theme").Returns(false); - _mockThemeService.GetBundledThemeArchivePaths().Returns([]); - _mockThemeService.RestoreBundledThemeAsync("bundled-theme", Arg.Any()) - .Returns(Task.FromException>(new IOException("The theme storage is locked."))); - _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.From(Result.Updated)); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeService.Received(1).RestoreBundledThemeAsync("bundled-theme", Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenLastBundledThemePackCannotBeRestored_ShouldKeepAndActivateTheTheme() - { - // Arrange - ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "bundled-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([brokenTheme])); - _mockThemeService.HasThemePack("bundled-theme").Returns(false); - _mockThemeService.GetBundledThemeArchivePaths().Returns([]); - _mockThemeService.RestoreBundledThemeAsync("bundled-theme", Arg.Any()).Returns(Error.Failure("Theme.Files", "restore failed")); - _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.From(Result.Updated)); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeRepository.Received(1).UpdateAsync( - Arg.Is(theme => theme.ThemeId == "bundled-theme" && theme.IsCurrent == true && !theme.IsDeleted), - Arg.Any()); - await _mockThemeService.Received(1).RestoreBundledThemeAsync("bundled-theme", Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenMissingBundledThemePackCannotBeRestoredAndAnotherBundledThemeRemains_ShouldSoftDeleteTheTheme() - { - // Arrange - ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "broken-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false); - ThemeEntity healthyTheme = _themeEntityFixture.Create(themeId: "healthy-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([brokenTheme, healthyTheme])); - _mockThemeService.HasThemePack("broken-theme").Returns(false); - _mockThemeService.GetBundledThemeArchivePaths().Returns([]); - _mockThemeService.RestoreBundledThemeAsync("broken-theme", Arg.Any()).Returns(Error.Failure("Theme.Files", "restore failed")); - _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.From(Result.Updated)); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeRepository.Received(1).UpdateAsync( - Arg.Is(theme => theme.ThemeId == "broken-theme" && theme.IsDeleted && theme.IsCurrent == null), - Arg.Any()); - await _mockThemeRepository.Received(1).UpdateAsync( - Arg.Is(theme => theme.ThemeId == "healthy-theme" && theme.IsCurrent == true), - Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenMissingUserThemePackExists_ShouldDeleteTheTheme() - { - // Arrange - ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "user-theme", installSource: ThemeInstallSource.Uploaded, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([brokenTheme])); - _mockThemeService.HasThemePack("user-theme").Returns(false); - _mockThemeService.GetBundledThemeArchivePaths().Returns([]); - _mockThemeRepository.DeleteByIdAsync(brokenTheme.Id, Arg.Any()).Returns(Result.From(Result.Deleted)); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeRepository.Received(1).DeleteByIdAsync(brokenTheme.Id, Arg.Any()); - await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenDeletingMissingUserThemeFails_ShouldLogWarningAndContinue() - { - // Arrange - ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "user-theme", installSource: ThemeInstallSource.Uploaded, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([brokenTheme])); - _mockThemeService.HasThemePack("user-theme").Returns(false); - _mockThemeService.GetBundledThemeArchivePaths().Returns([]); - _mockThemeRepository.DeleteByIdAsync(brokenTheme.Id, Arg.Any()).Returns(Error.Failure("Database.Error", "delete failed")); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeRepository.Received(1).DeleteByIdAsync(brokenTheme.Id, Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenNoThemeIsCurrent_ShouldActivateTheDefaultTheme() - { - // Arrange - ThemeEntity theme = _themeEntityFixture.Create(themeId: "default-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([theme])); - _mockThemeService.DefaultThemeId.Returns("default-theme"); - _mockThemeService.GetBundledThemeArchivePaths().Returns([]); - _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.From(Result.Updated)); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeRepository.Received(1).UpdateAsync( - Arg.Is(candidate => candidate.ThemeId == "default-theme" && candidate.IsCurrent == true), - Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenNoThemeIsCurrent_ShouldPreferTheConfiguredDefaultTheme() - { - // Arrange - ThemeEntity firstTheme = _themeEntityFixture.Create(themeId: "alpha-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false); - ThemeEntity defaultTheme = _themeEntityFixture.Create(themeId: "default-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([firstTheme, defaultTheme])); - _mockThemeService.DefaultThemeId.Returns("default-theme"); - _mockThemeService.GetBundledThemeArchivePaths().Returns([]); - _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.From(Result.Updated)); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeRepository.Received(1).UpdateAsync( - Arg.Is(candidate => candidate.ThemeId == "default-theme" && candidate.IsCurrent == true), - Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenAThemeIsAlreadyCurrent_ShouldNotChangeActivation() - { - // Arrange - ThemeEntity theme = _themeEntityFixture.Create(themeId: "current-theme", isCurrent: true, includeIsCurrent: true, installSource: ThemeInstallSource.Bundled, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([theme])); - _mockThemeService.GetBundledThemeArchivePaths().Returns([]); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeRepository.DidNotReceiveWithAnyArgs().UpdateAsync(default!, Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenBundledThemeArchiveFileCannotBeOpened_ShouldLogWarningAndContinue() - { - // Arrange - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); - string missingArchivePath = Path.Combine(_testRootPath, "bundled", "missing.zip"); - _mockThemeService.GetBundledThemeArchivePaths().Returns([missingArchivePath]); - _mockThemeService.ReadManifestFromArchiveAsync(missingArchivePath, Arg.Any()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme")); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); - await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenBundledThemeArchivePathIsADirectory_ShouldLogWarningAndContinue() - { - // Arrange - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); - string directoryPath = Path.Combine(_testRootPath, "not-an-archive"); - Directory.CreateDirectory(directoryPath); - _mockThemeService.GetBundledThemeArchivePaths().Returns([directoryPath]); - _mockThemeService.ReadManifestFromArchiveAsync(directoryPath, Arg.Any()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme")); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); - await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenSoftDeletingUnrestorableBundledThemeFails_ShouldLogWarningAndContinue() - { - // Arrange - ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "broken-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false); - ThemeEntity healthyTheme = _themeEntityFixture.Create(themeId: "healthy-theme", isCurrent: true, includeIsCurrent: true, installSource: ThemeInstallSource.Bundled, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([brokenTheme, healthyTheme])); - _mockThemeService.HasThemePack("broken-theme").Returns(false); - _mockThemeService.GetBundledThemeArchivePaths().Returns([]); - _mockThemeService.RestoreBundledThemeAsync("broken-theme", Arg.Any()).Returns(Error.Failure("Theme.Files", "restore failed")); - _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Error.Failure("Database.Error", "update failed")); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeRepository.Received(1).UpdateAsync( - Arg.Is(theme => theme.ThemeId == "broken-theme" && theme.IsDeleted && theme.IsCurrent == null), - Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenCancellationIsRequestedWhileCleaningUp_ShouldLetTheCancellationPropagate() - { - // Arrange - ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "user-theme", installSource: ThemeInstallSource.Uploaded, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([brokenTheme])); - _mockThemeService.HasThemePack("user-theme").Returns(false); - _mockThemeService.GetBundledThemeArchivePaths().Returns([]); - _mockThemeRepository.DeleteByIdAsync(brokenTheme.Id, Arg.Any()) - .Returns(Task.FromException>(new OperationCanceledException())); - - // Act - Task executionTask = StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await Assert.ThrowsAnyAsync(() => executionTask); - await _mockUnitOfWork.DidNotReceiveWithAnyArgs().SaveChangesAsync(Arg.Any()); - } - - /// - /// Invokes the protected of the job and awaits its completion. - /// - /// The job to execute. - private static async Task StartAndWaitForExecutionAsync(ThemeDetectionSyncJob sut) - { - MethodInfo executeAsyncMethod = typeof(ThemeDetectionSyncJob).GetMethod("ExecuteAsync", BindingFlags.Instance | BindingFlags.NonPublic)!; - Task executingTask = (Task)executeAsyncMethod.Invoke(sut, [CancellationToken.None])!; - await executingTask; - } - - /// - /// Creates the system under test wired to the mocked dependencies. - /// - /// The created job instance. - private ThemeDetectionSyncJob CreateSut() - { - return new ThemeDetectionSyncJob(_mockServiceScopeFactory, _mockThemeService, _mockLogger); - } - - /// - /// Writes a bundled theme archive file into the per-test temporary directory. - /// - /// The theme id of the bundled archive. - /// The path of the written archive. - private string CreateBundledArchiveFile(string themeId) - { - string bundledPath = Path.Combine(_testRootPath, "bundled"); - Directory.CreateDirectory(bundledPath); - string archivePath = Path.Combine(bundledPath, $"{themeId}.zip"); - File.WriteAllBytes(archivePath, _themePackFixture.Create(themeId: themeId)); - return archivePath; - } -} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs new file mode 100644 index 00000000..af45a663 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs @@ -0,0 +1,498 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Themes; +using Lumina.Application.Common.DataAccess.Repositories.Themes; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Models.DTO.Themes; +using Lumina.Application.Common.Infrastructure.Themes; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; +using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Themes; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Themes; +using Lumina.Infrastructure.Core.Themes; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Themes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeSynchronizerTests : IDisposable +{ + private readonly IThemeService _mockThemeService; + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IThemeRepository _mockThemeRepository; + private readonly ILogger _mockLogger; + private readonly ThemeEntityFixture _themeEntityFixture = new(); + private readonly ThemeManifestDtoFixture _themeManifestDtoFixture = new(); + private readonly string _temporaryDirectoryPath; + + /// + /// Initializes a new instance of the class. + /// + public ThemeSynchronizerTests() + { + _mockThemeService = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockThemeRepository = Substitute.For(); + _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockLogger = Substitute.For(); + _mockThemeService.GetBundledThemeArchivePaths().Returns([]); + _mockThemeService.HasThemePack(Arg.Any()).Returns(true); + _mockThemeService.DefaultThemeId.Returns("lumina-default"); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From(Enumerable.Empty())); + _mockThemeRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Created); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); + _mockThemeRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()).Returns(Result.Deleted); + _temporaryDirectoryPath = Path.Combine(Path.GetTempPath(), $"lumina-theme-sync-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_temporaryDirectoryPath); + } + + [Fact] + public async Task SynchronizeAsync_WhenTheInstalledThemesCannotBeRead_ShouldLogAndReturn() + { + // Arrange + _mockThemeRepository.GetAllAsync(Arg.Any()) + .Returns(Error.Failure("Themes.NotFound", "Failed to read the installed themes")); + _mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + await _mockThemeService.DidNotReceive().ReadManifestFromArchiveAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task SynchronizeAsync_WhenABundledArchiveManifestCannotBeRead_ShouldSkipThatArchive() + { + // Arrange + _mockThemeService.GetBundledThemeArchivePaths().Returns(["missing.zip"]); + _mockThemeService.ReadManifestFromArchiveAsync("missing.zip", Arg.Any()) + .Returns(Error.Failure("Theme.Manifest", "Failed to read the theme manifest")); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task SynchronizeAsync_WhenTheBundledThemeIsAlreadyInstalled_ShouldNotReinstallIt() + { + // Arrange + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); + ThemeEntity installedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { installedTheme }); + _mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]); + _mockThemeService.ReadManifestFromArchiveAsync("bundled.zip", Arg.Any()).Returns(Result.From(manifest)); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task SynchronizeAsync_WhenTheBundledThemeWasSoftDeletedByTheUser_ShouldNotReinstallIt() + { + // Arrange + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); + ThemeEntity deletedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: true); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { deletedTheme }); + _mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]); + _mockThemeService.ReadManifestFromArchiveAsync("bundled.zip", Arg.Any()).Returns(Result.From(manifest)); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task SynchronizeAsync_WhenABundledThemeIsMissingItsFiles_ShouldReinstallThemWithoutAddingANewRow() + { + // Arrange + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); + ThemeEntity damagedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { damagedTheme }); + string archivePath = CreateArchiveFile(); + _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); + // The first pack check happens before the repair and reports the files as missing; the later checks report the files as present. + _mockThemeService.HasThemePack(damagedTheme.ThemeId).Returns(false, true); + _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(Result.From(manifest)); + _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).Returns(Result.From(manifest)); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + await _mockThemeService.Received(1).InstallAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task SynchronizeAsync_WhenTheReinstallationFails_ShouldLogAndKeepTheExistingTheme() + { + // Arrange + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); + ThemeEntity damagedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { damagedTheme }); + string archivePath = CreateArchiveFile(); + _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); + _mockThemeService.HasThemePack(damagedTheme.ThemeId).Returns(false, true); + _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(Result.From(manifest)); + _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Theme.Install", "Failed to install the theme")); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + await _mockThemeService.Received(1).InstallAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task SynchronizeAsync_WhenANewBundledThemeIsInstalled_ShouldInsertTheThemeRow() + { + // Arrange + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); + string archivePath = CreateArchiveFile(); + _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); + _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(Result.From(manifest)); + _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).Returns(Result.From(manifest)); + _mockThemeService.HasThemePack(manifest.Id).Returns(true); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + await _mockThemeRepository.Received(1).InsertAsync(Arg.Is(theme => theme.ThemeId == manifest.Id && theme.InstallSource == ThemeInstallSource.Bundled), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task SynchronizeAsync_WhenPersistingANewBundledThemeFails_ShouldLogAndContinue() + { + // Arrange + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); + string archivePath = CreateArchiveFile(); + _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); + _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(Result.From(manifest)); + _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).Returns(Result.From(manifest)); + _mockThemeService.HasThemePack(manifest.Id).Returns(true); + _mockThemeRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Themes.InsertFailed", "Failed to insert the theme")); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + await _mockThemeRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task SynchronizeAsync_WhenTheArchiveFileCannotBeRead_ShouldLogAndContinue() + { + // Arrange + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); + string missingArchivePath = Path.Combine(_temporaryDirectoryPath, "missing.zip"); + _mockThemeService.GetBundledThemeArchivePaths().Returns([missingArchivePath]); + _mockThemeService.ReadManifestFromArchiveAsync(missingArchivePath, Arg.Any()).Returns(Result.From(manifest)); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task SynchronizeAsync_WhenAccessToTheArchiveFileIsDenied_ShouldLogAndContinue() + { + // On non Windows platforms opening a directory behaves differently, so the test only asserts the denied access path on Windows. + if (!OperatingSystem.IsWindows()) + return; + + // Arrange + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); + string deniedArchivePath = _temporaryDirectoryPath; + _mockThemeService.GetBundledThemeArchivePaths().Returns([deniedArchivePath]); + _mockThemeService.ReadManifestFromArchiveAsync(deniedArchivePath, Arg.Any()).Returns(Result.From(manifest)); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task SynchronizeAsync_WhenAllThemesAreHealthyAndNoArchiveIsBundled_ShouldOnlyPersistTheChanges() + { + // Arrange + ThemeEntity healthyTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { healthyTheme }); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task SynchronizeAsync_WhenABundledThemeIsBroken_ShouldRestoreItsFiles() + { + // Arrange + ThemeEntity brokenTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { brokenTheme }); + _mockThemeService.HasThemePack(brokenTheme.ThemeId).Returns(false); + _mockThemeService.RestoreBundledThemeAsync(brokenTheme.ThemeId, Arg.Any()).Returns(Result.Success); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + await _mockThemeService.Received(1).RestoreBundledThemeAsync(brokenTheme.ThemeId, Arg.Any()); + await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task SynchronizeAsync_WhenTheLastBundledThemeCannotBeRestored_ShouldKeepIt() + { + // Arrange + ThemeEntity lastBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { lastBundledTheme }); + _mockThemeService.HasThemePack(lastBundledTheme.ThemeId).Returns(false); + _mockThemeService.RestoreBundledThemeAsync(lastBundledTheme.ThemeId, Arg.Any()) + .Returns(Error.Failure("Theme.Restore", "Failed to restore the theme")); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + Assert.False(lastBundledTheme.IsDeleted); + await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task SynchronizeAsync_WhenABundledThemeCannotBeRestored_ShouldSoftDeleteIt() + { + // Arrange + ThemeEntity brokenBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false); + ThemeEntity healthyBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { brokenBundledTheme, healthyBundledTheme }); + _mockThemeService.HasThemePack(brokenBundledTheme.ThemeId).Returns(false); + _mockThemeService.RestoreBundledThemeAsync(brokenBundledTheme.ThemeId, Arg.Any()) + .Returns(Error.Failure("Theme.Restore", "Failed to restore the theme")); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + Assert.True(brokenBundledTheme.IsDeleted); + await _mockThemeRepository.Received(1).UpdateAsync(Arg.Is(theme => theme.Id == brokenBundledTheme.Id), Arg.Any()); + await _mockThemeRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task SynchronizeAsync_WhenSoftDeletingABrokenBundledThemeFails_ShouldLogAndContinue() + { + // Arrange + ThemeEntity brokenBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false); + ThemeEntity healthyBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { brokenBundledTheme, healthyBundledTheme }); + _mockThemeService.HasThemePack(brokenBundledTheme.ThemeId).Returns(false); + _mockThemeService.RestoreBundledThemeAsync(brokenBundledTheme.ThemeId, Arg.Any()) + .Returns(Error.Failure("Theme.Restore", "Failed to restore the theme")); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Themes.UpdateFailed", "Failed to update the theme")); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + await _mockThemeRepository.Received(1).UpdateAsync(Arg.Is(theme => theme.Id == brokenBundledTheme.Id), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task SynchronizeAsync_WhenAUserThemeIsBroken_ShouldDeleteIt() + { + // Arrange + ThemeEntity brokenUserTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false, includeIsCurrent: true, isCurrent: true); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { brokenUserTheme }); + _mockThemeService.HasThemePack(brokenUserTheme.ThemeId).Returns(false); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + await _mockThemeRepository.Received(1).DeleteByIdAsync(brokenUserTheme.Id, Arg.Any()); + } + + [Fact] + public async Task SynchronizeAsync_WhenDeletingABrokenUserThemeFails_ShouldLogAndContinue() + { + // Arrange + ThemeEntity brokenUserTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false, includeIsCurrent: true, isCurrent: true); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { brokenUserTheme }); + _mockThemeService.HasThemePack(brokenUserTheme.ThemeId).Returns(false); + _mockThemeRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Themes.DeleteFailed", "Failed to delete the theme")); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + await _mockThemeRepository.Received(1).DeleteByIdAsync(brokenUserTheme.Id, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task SynchronizeAsync_WhenRepairingOneBrokenThemeThrows_ShouldContinueWithTheRemainingBrokenThemes() + { + // Arrange + ThemeEntity throwingBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false); + ThemeEntity healthyBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { throwingBundledTheme, healthyBundledTheme }); + _mockThemeService.HasThemePack(Arg.Any()).Returns(false); + _mockThemeService.RestoreBundledThemeAsync(throwingBundledTheme.ThemeId, Arg.Any()) + .Returns(Task.FromException>(new InvalidOperationException("Unexpected failure"))); + _mockThemeService.RestoreBundledThemeAsync(healthyBundledTheme.ThemeId, Arg.Any()) + .Returns(Error.Failure("Theme.Restore", "Failed to restore the theme")); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + // The second broken bundled theme is still soft deleted even though the first one threw. + Assert.True(healthyBundledTheme.IsDeleted); + await _mockThemeRepository.Received(1).UpdateAsync(Arg.Is(theme => theme.Id == healthyBundledTheme.Id), Arg.Any()); + } + + [Fact] + public async Task SynchronizeAsync_WhenRepairingABrokenThemeIsCancelled_ShouldRethrowTheCancellation() + { + // Arrange + ThemeEntity brokenBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { brokenBundledTheme }); + _mockThemeService.HasThemePack(brokenBundledTheme.ThemeId).Returns(false); + _mockThemeService.RestoreBundledThemeAsync(brokenBundledTheme.ThemeId, Arg.Any()) + .Returns(Task.FromException>(new OperationCanceledException())); + + // Act + async Task Act() + { + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task EnsureCurrentThemeExistsAsync_WhenANonDeletedThemeIsCurrent_ShouldNotSelectAnotherTheme() + { + // Arrange + ThemeEntity currentTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); + ThemeEntity otherTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false); + + // Act + await InvokeEnsureCurrentThemeExistsAsync([currentTheme, otherTheme]); + + // Assert + Assert.True(currentTheme.IsCurrent); + Assert.NotEqual(true, otherTheme.IsCurrent); + await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnsureCurrentThemeExistsAsync_WhenNoThemeCanBeSelected_ShouldNotSelectAnyTheme() + { + // Arrange + ThemeEntity deletedTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: true); + + // Act + await InvokeEnsureCurrentThemeExistsAsync([deletedTheme]); + + // Assert + Assert.NotEqual(true, deletedTheme.IsCurrent); + await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnsureCurrentThemeExistsAsync_WhenNoThemeIsCurrent_ShouldActivateTheDefaultTheme() + { + // Arrange + ThemeEntity defaultTheme = _themeEntityFixture.Create(themeId: "lumina-default", installSource: ThemeInstallSource.Bundled, isDeleted: false); + ThemeEntity userTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false); + _mockThemeService.HasThemePack(defaultTheme.ThemeId).Returns(true); + _mockThemeService.HasThemePack(userTheme.ThemeId).Returns(false); + + // Act + await InvokeEnsureCurrentThemeExistsAsync([userTheme, defaultTheme]); + + // Assert + Assert.True(defaultTheme.IsCurrent); + await _mockThemeRepository.Received(1).UpdateAsync(Arg.Is(theme => theme.Id == defaultTheme.Id), Arg.Any()); + } + + /// + /// Creates a real archive file on disk so that can open it. + /// + /// The path of the created archive file. + private string CreateArchiveFile() + { + string archivePath = Path.Combine(_temporaryDirectoryPath, $"theme-{Guid.NewGuid():N}.zip"); + File.WriteAllText(archivePath, "theme-pack"); + return archivePath; + } + + /// + /// Invokes the private EnsureCurrentThemeExistsAsync method of the synchronizer. + /// + /// The installed themes passed to the method. + /// A task that represents the asynchronous operation. + private async Task InvokeEnsureCurrentThemeExistsAsync(IReadOnlyList themes) + { + MethodInfo method = typeof(ThemeSynchronizer).GetMethod("EnsureCurrentThemeExistsAsync", BindingFlags.Static | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("The method 'EnsureCurrentThemeExistsAsync' was not found on the theme synchronizer."); + Task task = (Task)method.Invoke(null, [_mockThemeService, _mockUnitOfWork, themes, CancellationToken.None])!; + await task.ConfigureAwait(false); + } + + /// + /// Removes the temporary files created by the tests. + /// + public void Dispose() + { + if (Directory.Exists(_temporaryDirectoryPath)) + Directory.Delete(_temporaryDirectoryPath, recursive: true); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/AddScheduledJob/AddScheduledJobEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/AddScheduledJob/AddScheduledJobEndpointTests.cs new file mode 100644 index 00000000..4043ca70 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/AddScheduledJob/AddScheduledJobEndpointTests.cs @@ -0,0 +1,159 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Domain.Common.Errors; +using Lumina.Application.Core.Scheduling.Commands.AddScheduledJob; +using Lumina.Contracts.Fixtures.Core.Requests.Scheduling; +using Lumina.Contracts.Fixtures.Core.Responses.Scheduling; +using Lumina.Contracts.Requests.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using Lumina.Presentation.Api.Core.Endpoints.Scheduling.AddScheduledJob; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Scheduling.AddScheduledJob; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddScheduledJobEndpointTests +{ + private readonly Application.Common.CQRS.ICommandHandler> _mockHandler; + private readonly AddScheduledJobEndpoint _sut; + private readonly AddScheduledJobRequestFixture _addScheduledJobRequestFixture = new(); + private readonly ScheduledJobResponseFixture _scheduledJobResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public AddScheduledJobEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithScheduledJobResponse() + { + // Arrange + AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create(name: "Scan job", scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + CancellationToken cancellationToken = CancellationToken.None; + ScheduledJobResponse expectedResponse = _scheduledJobResponseFixture.Create( + name: request.Name, + taskType: request.TaskType, + scheduleType: request.ScheduleType, + intervalMinutes: request.IntervalMinutes, + hour: request.Hour, + minute: request.Minute, + status: ScheduledJobStatus.Added); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Lumina.Domain.Common.Errors.Errors.Scheduling.ScheduledJobNameCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Assert.NotNull(problemResult.ProblemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendMappedCommandToHandler() + { + // Arrange + AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create( + name: "Mapped job", + taskType: ScheduledTaskType.CleanTemporaryFiles, + scheduleType: ScheduleType.DailyAtHourAndMinute, + hour: 2, + minute: 15); + CancellationToken cancellationToken = CancellationToken.None; + ScheduledJobResponse response = _scheduledJobResponseFixture.Create( + name: request.Name, + taskType: request.TaskType, + scheduleType: request.ScheduleType, + hour: request.Hour, + minute: request.Minute, + status: ScheduledJobStatus.Added); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(response)); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.Name == request.Name && + command.TaskType == request.TaskType && + command.ScheduleType == request.ScheduleType && + command.IntervalMinutes == request.IntervalMinutes && + command.Hour == request.Hour && + command.Minute == request.Minute), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + ScheduledJobResponse response = _scheduledJobResponseFixture.Create( + name: request.Name, + taskType: request.TaskType, + scheduleType: request.ScheduleType, + intervalMinutes: request.IntervalMinutes, + hour: request.Hour, + minute: request.Minute, + status: ScheduledJobStatus.Added); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(response); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/FireScheduledJob/FireScheduledJobEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/FireScheduledJob/FireScheduledJobEndpointTests.cs new file mode 100644 index 00000000..3be065a6 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/FireScheduledJob/FireScheduledJobEndpointTests.cs @@ -0,0 +1,164 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Domain.Common.Errors; +using Lumina.Application.Core.Scheduling.Commands.FireScheduledJob; +using Lumina.Contracts.Fixtures.Core.Requests.Scheduling; +using Lumina.Contracts.Fixtures.Core.Responses.Scheduling; +using Lumina.Contracts.Requests.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using Lumina.Presentation.Api.Core.Endpoints.Scheduling.FireScheduledJob; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Scheduling.FireScheduledJob; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class FireScheduledJobEndpointTests +{ + private readonly Application.Common.CQRS.ICommandHandler> _mockHandler; + private readonly FireScheduledJobEndpoint _sut; + private readonly FireScheduledJobRequestFixture _fireScheduledJobRequestFixture = new(); + private readonly ScheduledJobResponseFixture _scheduledJobResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public FireScheduledJobEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithScheduledJobResponse() + { + // Arrange + FireScheduledJobRequest request = _fireScheduledJobRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ScheduledJobResponse expectedResponse = _scheduledJobResponseFixture.Create( + id: request.ScheduledJobId, + name: "Scan job", + taskType: ScheduledTaskType.ScanMediaLibraries, + scheduleType: ScheduleType.WithIntervalInMinutes, + intervalMinutes: 60, + status: ScheduledJobStatus.Active); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + FireScheduledJobRequest request = _fireScheduledJobRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Errors.Scheduling.ScheduledJobNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Assert.NotNull(problemResult.ProblemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorized_ShouldReturnForbiddenProblemResult() + { + // Arrange + FireScheduledJobRequest request = _fireScheduledJobRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Authorization.NotAuthorized); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendMappedCommandToHandler() + { + // Arrange + FireScheduledJobRequest request = _fireScheduledJobRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ScheduledJobResponse response = _scheduledJobResponseFixture.Create( + id: request.ScheduledJobId, + name: "Scan job", + taskType: ScheduledTaskType.ScanMediaLibraries, + scheduleType: ScheduleType.WithIntervalInMinutes, + intervalMinutes: 60, + status: ScheduledJobStatus.Active); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(response)); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.ScheduledJobId == request.ScheduledJobId), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + FireScheduledJobRequest request = _fireScheduledJobRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + ScheduledJobResponse response = _scheduledJobResponseFixture.Create( + id: request.ScheduledJobId, + name: "Scan job", + taskType: ScheduledTaskType.ScanMediaLibraries, + scheduleType: ScheduleType.WithIntervalInMinutes, + intervalMinutes: 60, + status: ScheduledJobStatus.Active); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(response); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs new file mode 100644 index 00000000..f0873f97 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs @@ -0,0 +1,97 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Scheduling.Queries.GetScheduledJobHistory; +using Lumina.Contracts.Fixtures.Core.Requests.Scheduling; +using Lumina.Contracts.Fixtures.Core.Responses.Scheduling; +using Lumina.Contracts.Requests.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Scheduling.GetScheduledJobHistory; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Scheduling.GetScheduledJobHistory; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetScheduledJobHistoryEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetScheduledJobHistoryEndpoint _sut; + private readonly GetScheduledJobHistoryRequestFixture _getScheduledJobHistoryRequestFixture = new(); + private readonly ScheduledJobExecutionResponseFixture _scheduledJobExecutionResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetScheduledJobHistoryEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithExecutionResponses() + { + // Arrange + GetScheduledJobHistoryRequest request = _getScheduledJobHistoryRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + List expectedResponses = _scheduledJobExecutionResponseFixture.CreateMany(2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>(expectedResponses)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(2, okResult.Value.Count()); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + GetScheduledJobHistoryRequest request = _getScheduledJobHistoryRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Authorization.NotAuthorized); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendMappedQueryToHandler() + { + // Arrange + GetScheduledJobHistoryRequest request = _getScheduledJobHistoryRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.From == request.From && query.To == request.To), + Arg.Is(cancellationToken)); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/GetScheduledJobs/GetScheduledJobsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/GetScheduledJobs/GetScheduledJobsEndpointTests.cs new file mode 100644 index 00000000..516be193 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/GetScheduledJobs/GetScheduledJobsEndpointTests.cs @@ -0,0 +1,90 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Scheduling.Queries.GetScheduledJobs; +using Lumina.Contracts.Fixtures.Core.Responses.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Scheduling.GetScheduledJobs; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Scheduling.GetScheduledJobs; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetScheduledJobsEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetScheduledJobsEndpoint _sut; + private readonly ScheduledJobResponseFixture _scheduledJobResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetScheduledJobsEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithScheduledJobResponses() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + List expectedResponses = _scheduledJobResponseFixture.CreateMany(2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>(expectedResponses)); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(2, okResult.Value.Count()); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Authorization.NotAuthorized); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendQueryToHandler() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Any(), + Arg.Is(cancellationToken)); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs new file mode 100644 index 00000000..eb46fc16 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs @@ -0,0 +1,88 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Scheduling.Queries.GetSchedulerDisplayPreferences; +using Lumina.Contracts.Fixtures.Core.Responses.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Scheduling.GetSchedulerDisplayPreferences; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Scheduling.GetSchedulerDisplayPreferences; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetSchedulerDisplayPreferencesEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetSchedulerDisplayPreferencesEndpoint _sut; + private readonly SchedulerDisplayPreferencesResponseFixture _schedulerDisplayPreferencesResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetSchedulerDisplayPreferencesEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDisplayPreferencesResponse() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + SchedulerDisplayPreferencesResponse expectedResponse = _schedulerDisplayPreferencesResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Authorization.NotAuthorized); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendQueryToHandler() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_schedulerDisplayPreferencesResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Any(), + Arg.Is(cancellationToken)); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs new file mode 100644 index 00000000..d9d0d9b3 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs @@ -0,0 +1,109 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob; +using Lumina.Contracts.Fixtures.Core.Requests.Scheduling; +using Lumina.Contracts.Requests.Scheduling; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Scheduling.RemoveScheduledJob; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Scheduling.RemoveScheduledJob; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RemoveScheduledJobEndpointTests +{ + private readonly Application.Common.CQRS.ICommandHandler> _mockHandler; + private readonly RemoveScheduledJobEndpoint _sut; + private readonly RemoveScheduledJobRequestFixture _removeScheduledJobRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public RemoveScheduledJobEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResult() + { + // Arrange + RemoveScheduledJobRequest request = _removeScheduledJobRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Success); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + IStatusCodeHttpResult statusCodeResult = Assert.IsAssignableFrom(result); + Assert.Equal(StatusCodes.Status200OK, statusCodeResult.StatusCode); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + RemoveScheduledJobRequest request = _removeScheduledJobRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Domain.Common.Errors.Errors.Scheduling.ScheduledJobNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorized_ShouldReturnForbiddenProblemResult() + { + // Arrange + RemoveScheduledJobRequest request = _removeScheduledJobRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Authorization.NotAuthorized); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendMappedCommandToHandler() + { + // Arrange + RemoveScheduledJobRequest request = _removeScheduledJobRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Success); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.ScheduledJobId == request.ScheduledJobId), + Arg.Is(cancellationToken)); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/StartScheduledJob/StartScheduledJobEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/StartScheduledJob/StartScheduledJobEndpointTests.cs new file mode 100644 index 00000000..77f70842 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/StartScheduledJob/StartScheduledJobEndpointTests.cs @@ -0,0 +1,115 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Core.Scheduling.Commands.StartScheduledJob; +using Lumina.Contracts.Fixtures.Core.Requests.Scheduling; +using Lumina.Contracts.Fixtures.Core.Responses.Scheduling; +using Lumina.Contracts.Requests.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using Lumina.Presentation.Api.Core.Endpoints.Scheduling.StartScheduledJob; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Scheduling.StartScheduledJob; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class StartScheduledJobEndpointTests +{ + private readonly Application.Common.CQRS.ICommandHandler> _mockHandler; + private readonly StartScheduledJobEndpoint _sut; + private readonly StartScheduledJobRequestFixture _startScheduledJobRequestFixture = new(); + private readonly ScheduledJobResponseFixture _scheduledJobResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public StartScheduledJobEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithScheduledJobResponse() + { + // Arrange + StartScheduledJobRequest request = _startScheduledJobRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ScheduledJobResponse expectedResponse = _scheduledJobResponseFixture.Create( + id: request.ScheduledJobId, + status: ScheduledJobStatus.Active); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + StartScheduledJobRequest request = _startScheduledJobRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Errors.Scheduling.ScheduledJobNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorized_ShouldReturnForbiddenProblemResult() + { + // Arrange + StartScheduledJobRequest request = _startScheduledJobRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Authorization.NotAuthorized); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendMappedCommandToHandler() + { + // Arrange + StartScheduledJobRequest request = _startScheduledJobRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_scheduledJobResponseFixture.Create(id: request.ScheduledJobId))); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.ScheduledJobId == request.ScheduledJobId), + Arg.Is(cancellationToken)); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/StopScheduledJob/StopScheduledJobEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/StopScheduledJob/StopScheduledJobEndpointTests.cs new file mode 100644 index 00000000..80c13a69 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/StopScheduledJob/StopScheduledJobEndpointTests.cs @@ -0,0 +1,115 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Core.Scheduling.Commands.StopScheduledJob; +using Lumina.Contracts.Fixtures.Core.Requests.Scheduling; +using Lumina.Contracts.Fixtures.Core.Responses.Scheduling; +using Lumina.Contracts.Requests.Scheduling; +using Lumina.Contracts.Responses.Scheduling; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using Lumina.Presentation.Api.Core.Endpoints.Scheduling.StopScheduledJob; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Scheduling.StopScheduledJob; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class StopScheduledJobEndpointTests +{ + private readonly Application.Common.CQRS.ICommandHandler> _mockHandler; + private readonly StopScheduledJobEndpoint _sut; + private readonly StopScheduledJobRequestFixture _stopScheduledJobRequestFixture = new(); + private readonly ScheduledJobResponseFixture _scheduledJobResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public StopScheduledJobEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithScheduledJobResponse() + { + // Arrange + StopScheduledJobRequest request = _stopScheduledJobRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ScheduledJobResponse expectedResponse = _scheduledJobResponseFixture.Create( + id: request.ScheduledJobId, + status: ScheduledJobStatus.Added); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + StopScheduledJobRequest request = _stopScheduledJobRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Errors.Scheduling.ScheduledJobNotStarted; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorized_ShouldReturnForbiddenProblemResult() + { + // Arrange + StopScheduledJobRequest request = _stopScheduledJobRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Authorization.NotAuthorized); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendMappedCommandToHandler() + { + // Arrange + StopScheduledJobRequest request = _stopScheduledJobRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_scheduledJobResponseFixture.Create(id: request.ScheduledJobId))); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.ScheduledJobId == request.ScheduledJobId), + Arg.Is(cancellationToken)); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs new file mode 100644 index 00000000..26a5f532 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs @@ -0,0 +1,112 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences; +using Lumina.Contracts.Fixtures.Core.Requests.Scheduling; +using Lumina.Contracts.Requests.Scheduling; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Scheduling.UpdateSchedulerDisplayPreferences; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Scheduling.UpdateSchedulerDisplayPreferences; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateSchedulerDisplayPreferencesEndpointTests +{ + private readonly Application.Common.CQRS.ICommandHandler> _mockHandler; + private readonly UpdateSchedulerDisplayPreferencesEndpoint _sut; + private readonly UpdateSchedulerDisplayPreferencesRequestFixture _updateSchedulerDisplayPreferencesRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdateSchedulerDisplayPreferencesEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithUpdated() + { + // Arrange + UpdateSchedulerDisplayPreferencesRequest request = _updateSchedulerDisplayPreferencesRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(Result.Updated, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + UpdateSchedulerDisplayPreferencesRequest request = _updateSchedulerDisplayPreferencesRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Scheduling.SchedulerDisplayTimeSpanMustBePositive; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorized_ShouldReturnForbiddenProblemResult() + { + // Arrange + UpdateSchedulerDisplayPreferencesRequest request = _updateSchedulerDisplayPreferencesRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Authorization.NotAuthorized); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendMappedCommandToHandler() + { + // Arrange + UpdateSchedulerDisplayPreferencesRequest request = _updateSchedulerDisplayPreferencesRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.JobTypeFilter == request.JobTypeFilter && + command.DisplayTimeSpan == request.DisplayTimeSpan && + command.DisplayTimeUnit == request.DisplayTimeUnit), + Arg.Is(cancellationToken)); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointTests.cs new file mode 100644 index 00000000..ffeedd01 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointTests.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.AddScheduledJob; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler.AddScheduledJob; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddScheduledJobEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly AddScheduledJobEndpoint _sut; + private readonly AddScheduledJobRequestFixture _addScheduledJobRequestFixture = new(); + private readonly ScheduledJobDtoFixture _scheduledJobDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public AddScheduledJobEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsCreatedJob_ShouldReturnSuccessJsonWithCreatedJob() + { + // Arrange + AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create(); + ScheduledJobDto expectedJob = _scheduledJobDtoFixture.Create(name: request.Name); + _mockApiHttpClient.PostAsync(ApiRoutes.ScheduledJobs.ADD_SCHEDULED_JOB, Arg.Any(), Arg.Any()) + .Returns(expectedJob); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(expectedJob.Name, jsonDocument.RootElement.GetProperty("data").GetProperty("name").GetString()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldForwardRequestToApiAndReturnSuccess() + { + // Arrange + AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create(); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_scheduledJobDtoFixture.Create()); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + ApiRoutes.ScheduledJobs.ADD_SCHEDULED_JOB, + Arg.Is(forwardedRequest => + forwardedRequest.Name == request.Name && + forwardedRequest.TaskType == request.TaskType && + forwardedRequest.ScheduleType == request.ScheduleType && + forwardedRequest.IntervalMinutes == request.IntervalMinutes && + forwardedRequest.Hour == request.Hour && + forwardedRequest.Minute == request.Minute), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs new file mode 100644 index 00000000..b79ee921 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.FireScheduledJob; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler.FireScheduledJob; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class FireScheduledJobEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly FireScheduledJobEndpoint _sut; + private readonly FireScheduledJobRequestFixture _fireScheduledJobRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public FireScheduledJobEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldFireScheduledJobViaApiAndReturnSuccess() + { + // Arrange + FireScheduledJobRequest request = _fireScheduledJobRequestFixture.Create(); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + string expectedEndpoint = ApiRoutes.ScheduledJobs.FIRE_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()); + await _mockApiHttpClient.Received(1).PutAsync( + expectedEndpoint, + Arg.Any(), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs new file mode 100644 index 00000000..d9f26ac3 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs @@ -0,0 +1,126 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.GetScheduledJobHistory; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler.GetScheduledJobHistory; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetScheduledJobHistoryEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetScheduledJobHistoryEndpoint _sut; + private readonly GetScheduledJobHistoryRequestFixture _getScheduledJobHistoryRequestFixture = new(); + private readonly ScheduledJobExecutionDtoFixture _scheduledJobExecutionDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetScheduledJobHistoryEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsExecutions_ShouldReturnSuccessJsonWithExecutions() + { + // Arrange + ScheduledJobExecutionDto[] expectedExecutions = [.. _scheduledJobExecutionDtoFixture.CreateMany(2)]; + _mockApiHttpClient.GetAsync(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOB_HISTORY, Arg.Any()) + .Returns(expectedExecutions); + + // Act + IResult result = await _sut.ExecuteAsync(_getScheduledJobHistoryRequestFixture.Create(), CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(expectedExecutions.Length, jsonDocument.RootElement.GetProperty("data").GetArrayLength()); + } + + [Fact] + public async Task ExecuteAsync_WhenFromAndToAreNull_ShouldRequestHistoryWithoutQueryString() + { + // Arrange + GetScheduledJobHistoryRequest request = _getScheduledJobHistoryRequestFixture.Create(); + _mockApiHttpClient.GetAsync(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOB_HISTORY, Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOB_HISTORY, Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenOnlyFromIsProvided_ShouldRequestHistoryWithFromQueryString() + { + // Arrange + DateTime from = new(2026, 1, 5, 4, 3, 2, DateTimeKind.Utc); + GetScheduledJobHistoryRequest request = _getScheduledJobHistoryRequestFixture.Create(from: from); + string expectedEndpoint = $"{ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOB_HISTORY}?from={Uri.EscapeDataString(from.ToString("o"))}"; + _mockApiHttpClient.GetAsync(expectedEndpoint, Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(expectedEndpoint, Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenOnlyToIsProvided_ShouldRequestHistoryWithToQueryString() + { + // Arrange + DateTime to = new(2026, 1, 5, 4, 3, 2, DateTimeKind.Utc); + GetScheduledJobHistoryRequest request = _getScheduledJobHistoryRequestFixture.Create(to: to); + string expectedEndpoint = $"{ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOB_HISTORY}?to={Uri.EscapeDataString(to.ToString("o"))}"; + _mockApiHttpClient.GetAsync(expectedEndpoint, Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(expectedEndpoint, Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenFromAndToAreProvided_ShouldRequestHistoryWithBothQueryStrings() + { + // Arrange + DateTime from = new(2026, 1, 5, 4, 3, 2, DateTimeKind.Utc); + DateTime to = new(2026, 1, 6, 4, 3, 2, DateTimeKind.Utc); + GetScheduledJobHistoryRequest request = _getScheduledJobHistoryRequestFixture.Create(from: from, to: to); + string expectedEndpoint = $"{ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOB_HISTORY}?from={Uri.EscapeDataString(from.ToString("o"))}&to={Uri.EscapeDataString(to.ToString("o"))}"; + _mockApiHttpClient.GetAsync(expectedEndpoint, Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(expectedEndpoint, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointTests.cs new file mode 100644 index 00000000..7f7b8997 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointTests.cs @@ -0,0 +1,73 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.GetScheduledJobs; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler.GetScheduledJobs; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetScheduledJobsEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetScheduledJobsEndpoint _sut; + private readonly ScheduledJobDtoFixture _scheduledJobDtoFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; + + /// + /// Initializes a new instance of the class. + /// + public GetScheduledJobsEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsJobs_ShouldReturnSuccessJsonWithScheduledJobs() + { + // Arrange + ScheduledJobDto[] expectedJobs = [.. _scheduledJobDtoFixture.CreateMany(2)]; + _mockApiHttpClient.GetAsync(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOBS, Arg.Any()) + .Returns(expectedJobs); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + ScheduledJobDto[]? returnedJobs = jsonDocument.RootElement.GetProperty("data").Deserialize(_jsonOptions); + Assert.Equal(expectedJobs.Length, returnedJobs!.Length); + Assert.Equal(expectedJobs.Select(job => job.Name), returnedJobs.Select(job => job.Name)); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestScheduledJobsFromApi() + { + // Arrange + _mockApiHttpClient.GetAsync(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOBS, Arg.Any()) + .Returns([.. _scheduledJobDtoFixture.CreateMany()]); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOBS, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs new file mode 100644 index 00000000..f264f66c --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs @@ -0,0 +1,69 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.GetSchedulerDisplayPreferences; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler.GetSchedulerDisplayPreferences; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetSchedulerDisplayPreferencesEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetSchedulerDisplayPreferencesEndpoint _sut; + private readonly SchedulerDisplayPreferencesDtoFixture _schedulerDisplayPreferencesDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetSchedulerDisplayPreferencesEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsPreferences_ShouldReturnSuccessJsonWithDisplayPreferences() + { + // Arrange + SchedulerDisplayPreferencesDto expectedPreferences = _schedulerDisplayPreferencesDtoFixture.Create(displayTimeUnit: Lumina.Presentation.Web.Common.Enums.Scheduling.SchedulerDisplayTimeUnit.Minutes); + _mockApiHttpClient.GetAsync(ApiRoutes.ScheduledJobs.GET_DISPLAY_PREFERENCES, Arg.Any()) + .Returns(expectedPreferences); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(expectedPreferences.UserId, jsonDocument.RootElement.GetProperty("data").GetProperty("userId").GetGuid()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestDisplayPreferencesFromApi() + { + // Arrange + _mockApiHttpClient.GetAsync(ApiRoutes.ScheduledJobs.GET_DISPLAY_PREFERENCES, Arg.Any()) + .Returns(_schedulerDisplayPreferencesDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.ScheduledJobs.GET_DISPLAY_PREFERENCES, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs new file mode 100644 index 00000000..4958c2a2 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.RemoveScheduledJob; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler.RemoveScheduledJob; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RemoveScheduledJobEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly RemoveScheduledJobEndpoint _sut; + private readonly RemoveScheduledJobRequestFixture _removeScheduledJobRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public RemoveScheduledJobEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRemoveScheduledJobViaApiAndReturnSuccess() + { + // Arrange + RemoveScheduledJobRequest request = _removeScheduledJobRequestFixture.Create(); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + string expectedEndpoint = ApiRoutes.ScheduledJobs.REMOVE_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()); + await _mockApiHttpClient.Received(1).DeleteAsync(expectedEndpoint, Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointTests.cs new file mode 100644 index 00000000..3045a4cd --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointTests.cs @@ -0,0 +1,140 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Http; +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler; +using Lumina.Presentation.Web.Core.Themes; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Configuration; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using Microsoft.Extensions.Options; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SchedulerIndexViewEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly IAntiforgery _mockAntiforgery; + private readonly IOptionsSnapshot _mockServerConfigurationOptions; + private readonly IUrlService _mockUrlService; + private readonly ThemePageRenderer _mockThemePageRenderer; + private readonly IStringLocalizerFactory _mockStringLocalizerFactory; + private readonly IStringLocalizer _mockStringLocalizer; + private readonly SchedulerIndexViewEndpoint _sut; + private readonly ServerConfigurationDtoFixture _serverConfigurationDtoFixture = new(); + private readonly ThemePageRenderResultDtoFixture _themePageRenderResultDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public SchedulerIndexViewEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _mockAntiforgery = Substitute.For(); + _mockAntiforgery.GetAndStoreTokens(Arg.Any()) + .Returns(new AntiforgeryTokenSet("test-request-token", "test-cookie-token", "__RequestVerificationToken", "RequestVerificationToken")); + _mockServerConfigurationOptions = Substitute.For>(); + _mockServerConfigurationOptions.Value.Returns(_serverConfigurationDtoFixture.Create(baseAddress: "http://localhost", port: 5214)); + _mockUrlService = Substitute.For(); + _mockThemePageRenderer = Substitute.For(new ThemeService(_mockApiHttpClient), new ThemeTemplateEngine()); + _mockStringLocalizer = Substitute.For(); + _mockStringLocalizer[Arg.Any()].Returns(callInfo => new LocalizedString(callInfo.Arg(), callInfo.Arg())); + _mockStringLocalizer.GetAllStrings(Arg.Any()).Returns( + [ + new LocalizedString("ScheduledJobs", "Scheduled Jobs"), + new LocalizedString("TaskType.ScanMediaLibraries", "Scan media libraries"), + new LocalizedString("TaskType.CleanTemporaryFiles", "Clean temporary files"), + new LocalizedString("TaskType.RepairThemes", "Repair themes"), + new LocalizedString("TaskType.CleanScheduledJobExecutionHistory", "Clean execution history"), + new LocalizedString("Status.Added", "Added"), + new LocalizedString("Status.Active", "Active"), + new LocalizedString("Status.Running", "Running"), + new LocalizedString("Status.Completed", "Completed") + ]); + _mockStringLocalizerFactory = Substitute.For(); + _mockStringLocalizerFactory.Create(Arg.Any(), Arg.Any()).Returns(_mockStringLocalizer); + _sut = Factory.Create(_mockAntiforgery, _mockServerConfigurationOptions, _mockUrlService, _mockThemePageRenderer, _mockStringLocalizerFactory); + TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession()); + _sut.HttpContext.Request.Path = "/en-us/admin/scheduled-jobs"; + } + + [Fact] + public async Task ExecuteAsync_WhenThemeRenderingSucceeds_ShouldRenderThemedPageThroughTheSharedView() + { + // Arrange + _mockUrlService.GetAbsoluteUrl(WebRoutes.Scheduler.GET_SCHEDULED_JOBS).Returns("http://localhost/en-us/admin/api-scheduled-jobs"); + _mockThemePageRenderer.RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_themePageRenderResultDtoFixture.Create(content: "
content
", script: ""))); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + Assert.IsType(result); + await _mockThemePageRenderer.Received(1).RenderAsync( + Arg.Is(page => + page.PageKey == "admin/scheduler" && + page.Title == "ScheduledJobs" && + string.Equals(page.PageData["scheduledJobsHubUrl"] as string, "http://localhost:5214/scheduledJobsHub", StringComparison.Ordinal) && + string.Equals(page.PageData["jobsListUrl"] as string, "http://localhost/en-us/admin/api-scheduled-jobs", StringComparison.Ordinal) && + string.Equals(page.PageData["antiforgeryToken"] as string, "test-request-token", StringComparison.Ordinal) && + page.PageData.ContainsKey("strings")), + Arg.Is(requestedThemeId => requestedThemeId == null), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenThemeRenderingFails_ShouldFallBackToRazorView() + { + // Arrange + _mockThemePageRenderer.RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.Failure(Error.Failure("Theme.Render", "The page could not be rendered."))); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + Assert.IsType(result); + await _mockThemePageRenderer.Received(1).RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldStoreAntiforgeryTokenAndRequestSchedulerUrls() + { + // Arrange + _mockUrlService.GetAbsoluteUrl(WebRoutes.Scheduler.GET_DISPLAY_PREFERENCES).Returns("http://localhost/en-us/admin/api-scheduled-jobs/display-preferences"); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Scheduler.START_SCHEDULED_JOB, Arg.Any()).Returns("http://localhost/en-us/admin/api-scheduled-jobs/00000000-0000-0000-0000-000000000000/start"); + _mockThemePageRenderer.RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_themePageRenderResultDtoFixture.Create())); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + _mockAntiforgery.Received(1).GetAndStoreTokens(_sut.HttpContext); + await _mockThemePageRenderer.Received(1).RenderAsync( + Arg.Is(page => + string.Equals(page.PageData["getDisplayPreferencesUrl"] as string, "http://localhost/en-us/admin/api-scheduled-jobs/display-preferences", StringComparison.Ordinal) && + string.Equals(page.PageData["startJobUrlTemplate"] as string, "http://localhost/en-us/admin/api-scheduled-jobs/00000000-0000-0000-0000-000000000000/start", StringComparison.Ordinal)), + Arg.Any(), + Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs new file mode 100644 index 00000000..0d2baa18 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.StartScheduledJob; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler.StartScheduledJob; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class StartScheduledJobEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly StartScheduledJobEndpoint _sut; + private readonly StartScheduledJobRequestFixture _startScheduledJobRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public StartScheduledJobEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldStartScheduledJobViaApiAndReturnSuccess() + { + // Arrange + StartScheduledJobRequest request = _startScheduledJobRequestFixture.Create(); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + string expectedEndpoint = ApiRoutes.ScheduledJobs.START_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()); + await _mockApiHttpClient.Received(1).PutAsync( + expectedEndpoint, + Arg.Any(), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs new file mode 100644 index 00000000..df66d913 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.StopScheduledJob; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler.StopScheduledJob; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class StopScheduledJobEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly StopScheduledJobEndpoint _sut; + private readonly StopScheduledJobRequestFixture _stopScheduledJobRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public StopScheduledJobEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldStopScheduledJobViaApiAndReturnSuccess() + { + // Arrange + StopScheduledJobRequest request = _stopScheduledJobRequestFixture.Create(); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + string expectedEndpoint = ApiRoutes.ScheduledJobs.STOP_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()); + await _mockApiHttpClient.Received(1).PutAsync( + expectedEndpoint, + Arg.Any(), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs new file mode 100644 index 00000000..c956a614 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.UpdateSchedulerDisplayPreferences; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler.UpdateSchedulerDisplayPreferences; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateSchedulerDisplayPreferencesEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly UpdateSchedulerDisplayPreferencesEndpoint _sut; + private readonly UpdateSchedulerDisplayPreferencesRequestFixture _updateSchedulerDisplayPreferencesRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdateSchedulerDisplayPreferencesEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldUpdateDisplayPreferencesViaApiAndReturnSuccess() + { + // Arrange + UpdateSchedulerDisplayPreferencesRequest request = _updateSchedulerDisplayPreferencesRequestFixture.Create(); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + await _mockApiHttpClient.Received(1).PutAsync( + ApiRoutes.ScheduledJobs.UPDATE_DISPLAY_PREFERENCES, + Arg.Is(forwardedRequest => + forwardedRequest.JobTypeFilter == request.JobTypeFilter && + forwardedRequest.DisplayTimeSpan == request.DisplayTimeSpan && + forwardedRequest.DisplayTimeUnit == request.DisplayTimeUnit), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } +}