Merge pull request #188 from BinaryAlley/feature/add-scheduler

This commit is contained in:
BinaryAlley authored and GitHub committed 2026-09-05 03:59:20 -07:00
commit 5753c11e2b
421 files changed
+34134 -900

No files matched your search

+1
View File
@@ -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
@@ -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
}
```
@@ -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")
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" data-diagram-type="DESCRIPTION" style="width:984px;height:1323px;background:#FFFFFF;" width="984px" height="1323px" viewBox="0 0 984 1323" zoomAndPan="magnify" preserveAspectRatio="none" contentStyleType="text/css"><?plantuml 1.2026.7?><defs/><g font-family="sans-serif" lengthAdjust="spacing"><g class="title" data-source-line="4"><text x="377.219" y="24.533" fill="#000" font-size="14" textLength="223.262" font-weight="700">Container diagram for Lumina 1.1</text></g><!--cluster c1--><g class="cluster" data-qualified-name="c1" id="ent0003" data-source-line="1666"><rect x="7" y="300.609" width="726" height="812.5" fill="none" style="stroke:#444;stroke-width:1;stroke-dasharray:7,7;"/><text x="328.211" y="319.219" fill="#444" font-size="16" textLength="83.578" font-weight="700">Lumina 1.1</text><text x="345.323" y="335.191" fill="#444" font-size="12" textLength="49.354" font-weight="700">[system]</text></g><!--entity webapp--><g class="entity" data-qualified-name="c1.webapp" id="ent0004" data-source-line="71"><rect x="343.5" y="354.609" width="252.996" height="198.609" fill="#438DD5" style="stroke:#3C7FC0;stroke-width:0.5;"/><text x="382.889" y="381.219" fill="#FFF" font-size="16" textLength="33.773" font-weight="700">Web</text><text x="416.662" y="381.219" fill="#FFF" font-size="16" font-weight="700"> </text><text x="421.107" y="381.219" fill="#FFF" font-size="16" textLength="87.109" font-weight="700">Application</text><text x="508.217" y="381.219" fill="#FFF" font-size="16" font-weight="700"> </text><text x="512.662" y="381.219" fill="#FFF" font-size="16" textLength="44.445" font-weight="700">Client</text><text x="458.877" y="401.344" fill="#FFF" font-size="16" textLength="22.242" font-weight="700">2.1</text><text x="411.319" y="417.316" fill="#FFF" font-size="12" textLength="54.68" font-style="italic">[ASP.NET</text><text x="465.999" y="417.316" fill="#FFF" font-size="12" font-style="italic"> </text><text x="469.333" y="417.316" fill="#FFF" font-size="12" textLength="26.01" font-style="italic">Core</text><text x="495.343" y="417.316" fill="#FFF" font-size="12" font-style="italic"> </text><text x="498.677" y="417.316" fill="#FFF" font-size="12" textLength="30" font-style="italic">MVC]</text><text x="468.053" y="434.486" fill="#FFF" font-size="14"> </text><text x="373.522" y="452.096" fill="#FFF" font-size="14" textLength="50.565">Delivers</text><text x="424.088" y="452.096" fill="#FFF" font-size="14"> </text><text x="427.978" y="452.096" fill="#FFF" font-size="14" textLength="99.6">server-rendered</text><text x="527.577" y="452.096" fill="#FFF" font-size="14"> </text><text x="531.467" y="452.096" fill="#FFF" font-size="14" textLength="35.007">views</text><text x="396.081" y="469.705" fill="#FFF" font-size="14" textLength="24.896">with</text><text x="420.978" y="469.705" fill="#FFF" font-size="14"> </text><text x="424.867" y="469.705" fill="#FFF" font-size="14" textLength="52.131">dynamic</text><text x="476.998" y="469.705" fill="#FFF" font-size="14"> </text><text x="480.888" y="469.705" fill="#FFF" font-size="14" textLength="63.027">client-side</text><text x="401.909" y="487.314" fill="#FFF" font-size="14" textLength="73.931">functionality</text><text x="475.839" y="487.314" fill="#FFF" font-size="14"> </text><text x="479.729" y="487.314" fill="#FFF" font-size="14" textLength="16.338">for</text><text x="496.067" y="487.314" fill="#FFF" font-size="14"> </text><text x="499.957" y="487.314" fill="#FFF" font-size="14" textLength="38.131">media</text><text x="385.943" y="504.924" fill="#FFF" font-size="14" textLength="81.717">management</text><text x="467.66" y="504.924" fill="#FFF" font-size="14"> </text><text x="471.55" y="504.924" fill="#FFF" font-size="14" textLength="23.358">and</text><text x="494.908" y="504.924" fill="#FFF" font-size="14"> </text><text x="498.798" y="504.924" fill="#FFF" font-size="14" textLength="55.255">playback</text><text x="423.127" y="522.533" fill="#FFF" font-size="14" textLength="52.931">[detailed</text><text x="476.058" y="522.533" fill="#FFF" font-size="14"> </text><text x="479.948" y="522.533" fill="#FFF" font-size="14" textLength="10.896">in</text><text x="490.844" y="522.533" fill="#FFF" font-size="14"> </text><text x="494.734" y="522.533" fill="#FFF" font-size="14" textLength="22.135">'3.1</text><text x="353.5" y="540.143" fill="#FFF" font-size="14" textLength="232.996">component-web-client-diagram.puml']</text></g><!--entity api--><g class="entity" data-qualified-name="c1.api" id="ent0005" data-source-line="71"><rect x="344" y="645.609" width="252.21" height="213.703" fill="#438DD5" style="stroke:#3C7FC0;stroke-width:0.5;"/><text x="416.292" y="672.219" fill="#FFF" font-size="16" textLength="26.672" font-weight="700">API</text><text x="442.964" y="672.219" fill="#FFF" font-size="16" font-weight="700"> </text><text x="447.41" y="672.219" fill="#FFF" font-size="16" tLine truncated
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" data-diagram-type="DESCRIPTION" style="width:980px;height:1400px;background:#FFFFFF;" width="980px" height="1400px" viewBox="0 0 980 1400" zoomAndPan="magnify" preserveAspectRatio="none" contentStyleType="text/css"><?plantuml 1.2026.7?><defs/><g font-family="sans-serif" lengthAdjust="spacing"><g class="title" data-source-line="4"><text x="375.219" y="24.533" fill="#000" font-size="14" textLength="223.262" font-weight="700">Container diagram for Lumina 1.1</text></g><!--cluster c1--><g class="cluster" data-qualified-name="c1" id="ent0003" data-source-line="1666"><rect x="7" y="300.609" width="722" height="889" fill="none" style="stroke:#444;stroke-width:1;stroke-dasharray:7,7;"/><text x="326.211" y="319.219" fill="#444" font-size="16" textLength="83.578" font-weight="700">Lumina 1.1</text><text x="343.323" y="335.191" fill="#444" font-size="12" textLength="49.354" font-weight="700">[system]</text></g><!--entity webapp--><g class="entity" data-qualified-name="c1.webapp" id="ent0004" data-source-line="71"><rect x="339.5" y="354.609" width="252.996" height="216.219" fill="#438DD5" style="stroke:#3C7FC0;stroke-width:0.5;"/><text x="378.889" y="381.219" fill="#FFF" font-size="16" textLength="33.773" font-weight="700">Web</text><text x="412.662" y="381.219" fill="#FFF" font-size="16" font-weight="700"> </text><text x="417.107" y="381.219" fill="#FFF" font-size="16" textLength="87.109" font-weight="700">Application</text><text x="504.217" y="381.219" fill="#FFF" font-size="16" font-weight="700"> </text><text x="508.662" y="381.219" fill="#FFF" font-size="16" textLength="44.445" font-weight="700">Client</text><text x="454.877" y="401.344" fill="#FFF" font-size="16" textLength="22.242" font-weight="700">2.1</text><text x="407.319" y="417.316" fill="#FFF" font-size="12" textLength="54.68" font-style="italic">[ASP.NET</text><text x="461.999" y="417.316" fill="#FFF" font-size="12" font-style="italic"> </text><text x="465.333" y="417.316" fill="#FFF" font-size="12" textLength="26.01" font-style="italic">Core</text><text x="491.343" y="417.316" fill="#FFF" font-size="12" font-style="italic"> </text><text x="494.677" y="417.316" fill="#FFF" font-size="12" textLength="30" font-style="italic">MVC]</text><text x="464.053" y="434.486" fill="#FFF" font-size="14"> </text><text x="369.522" y="452.096" fill="#FFF" font-size="14" textLength="50.565">Delivers</text><text x="420.088" y="452.096" fill="#FFF" font-size="14"> </text><text x="423.978" y="452.096" fill="#FFF" font-size="14" textLength="99.6">server-rendered</text><text x="523.577" y="452.096" fill="#FFF" font-size="14"> </text><text x="527.467" y="452.096" fill="#FFF" font-size="14" textLength="35.007">views</text><text x="392.081" y="469.705" fill="#FFF" font-size="14" textLength="24.896">with</text><text x="416.978" y="469.705" fill="#FFF" font-size="14"> </text><text x="420.867" y="469.705" fill="#FFF" font-size="14" textLength="52.131">dynamic</text><text x="472.998" y="469.705" fill="#FFF" font-size="14"> </text><text x="476.888" y="469.705" fill="#FFF" font-size="14" textLength="63.027">client-side</text><text x="397.909" y="487.314" fill="#FFF" font-size="14" textLength="73.931">functionality</text><text x="471.839" y="487.314" fill="#FFF" font-size="14"> </text><text x="475.729" y="487.314" fill="#FFF" font-size="14" textLength="16.338">for</text><text x="492.067" y="487.314" fill="#FFF" font-size="14"> </text><text x="495.957" y="487.314" fill="#FFF" font-size="14" textLength="38.131">media</text><text x="366.378" y="504.924" fill="#FFF" font-size="14" textLength="85.606">management,</text><text x="451.984" y="504.924" fill="#FFF" font-size="14"> </text><text x="455.874" y="504.924" fill="#FFF" font-size="14" textLength="59.145">playback,</text><text x="515.019" y="504.924" fill="#FFF" font-size="14"> </text><text x="518.908" y="504.924" fill="#FFF" font-size="14" textLength="23.358">and</text><text x="542.267" y="504.924" fill="#FFF" font-size="14"> </text><text x="546.156" y="504.924" fill="#FFF" font-size="14" textLength="19.462">the</text><text x="384.271" y="522.533" fill="#FFF" font-size="14" textLength="63.827">scheduled</text><text x="448.098" y="522.533" fill="#FFF" font-size="14"> </text><text x="451.988" y="522.533" fill="#FFF" font-size="14" textLength="25.683">jobs</text><text x="477.67" y="522.533" fill="#FFF" font-size="14"> </text><text x="481.56" y="522.533" fill="#FFF" font-size="14" textLength="66.165">dashboard</text><text x="419.127" y="540.143" fill="#FFF" font-size="14" textLength="52.931">[detailed</text><text x="472.058" y="540.143" fill="#FFF" font-size="14"> </text><text x="475.948" y="540.143" fill="#FFF" font-size="14" textLength="10.896">in</text><text x="486.844" y="540.143" fill="#FFF" font-size="14"> </text><text x="490.734" y="540.143" fill="#FFF" font-size="14" textLength="22.135">'3.1</text><text x="349.5" y="557.Line truncated

Before

Width:  |  Height:  |  Size: 39 KiB

After

Width:  |  Height:  |  Size: 42 KiB

@@ -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)
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" data-diagram-type="DESCRIPTION" style="width:1237px;height:1166px;background:#FFFFFF;" width="1237px" height="1166px" viewBox="0 0 1237 1166" zoomAndPan="magnify" preserveAspectRatio="none" contentStyleType="text/css"><?plantuml 1.2026.7?><defs/><g font-family="sans-serif" lengthAdjust="spacing"><g class="title" data-source-line="4"><text x="418.99" y="24.533" fill="#000" font-size="14" textLength="392.021" font-weight="700">Component diagram for Lumina Web Application Client 2.1</text></g><!--cluster wb--><g class="cluster" data-qualified-name="wb" id="ent0002" data-source-line="1666"><rect x="7" y="45.609" width="1216" height="654" fill="none" style="stroke:#444;stroke-width:1;stroke-dasharray:7,7;"/><text x="538.992" y="64.219" fill="#444" font-size="16" textLength="152.016" font-weight="700">Web Application 2.1</text><text x="583.998" y="80.191" fill="#444" font-size="12" textLength="62.004" font-weight="700">[container]</text></g><!--entity fileSystem--><g class="entity" data-qualified-name="wb.fileSystem" id="ent0003" data-source-line="78"><rect x="23" y="355.109" width="219.992" height="125.656" fill="#85BBF0" style="stroke:#78A8D8;stroke-width:0.5;"/><text x="37.41" y="381.719" fill="#000" font-size="16" textLength="27.563" font-weight="700">File</text><text x="64.973" y="381.719" fill="#000" font-size="16" font-weight="700"> </text><text x="69.418" y="381.719" fill="#000" font-size="16" textLength="56.922" font-weight="700">System</text><text x="126.34" y="381.719" fill="#000" font-size="16" font-weight="700"> </text><text x="130.785" y="381.719" fill="#000" font-size="16" textLength="97.797" font-weight="700">Management</text><text x="58.313" y="397.691" fill="#000" font-size="12" textLength="54.68" font-style="italic">[ASP.NET</text><text x="112.992" y="397.691" fill="#000" font-size="12" font-style="italic"> </text><text x="116.326" y="397.691" fill="#000" font-size="12" textLength="26.666" font-style="italic">MVC</text><text x="142.992" y="397.691" fill="#000" font-size="12" font-style="italic"> </text><text x="146.326" y="397.691" fill="#000" font-size="12" textLength="61.354" font-style="italic">Controllers]</text><text x="131.051" y="414.861" fill="#000" font-size="14"> </text><text x="37.672" y="432.471" fill="#000" font-size="14" textLength="51.365">Handles</text><text x="89.038" y="432.471" fill="#000" font-size="14"> </text><text x="92.927" y="432.471" fill="#000" font-size="14" textLength="17.896">file</text><text x="110.824" y="432.471" fill="#000" font-size="14"> </text><text x="114.713" y="432.471" fill="#000" font-size="14" textLength="44.338">system</text><text x="159.051" y="432.471" fill="#000" font-size="14"> </text><text x="162.941" y="432.471" fill="#000" font-size="14" textLength="65.379">operations</text><text x="33" y="450.08" fill="#000" font-size="14" textLength="55.262">including</text><text x="88.262" y="450.08" fill="#000" font-size="14"> </text><text x="92.151" y="450.08" fill="#000" font-size="14" textLength="41.234">drives,</text><text x="133.386" y="450.08" fill="#000" font-size="14"> </text><text x="137.275" y="450.08" fill="#000" font-size="14" textLength="68.469">directories,</text><text x="205.744" y="450.08" fill="#000" font-size="14"> </text><text x="209.634" y="450.08" fill="#000" font-size="14" textLength="23.358">and</text><text x="90.589" y="467.689" fill="#000" font-size="14" textLength="24.896">files</text><text x="115.486" y="467.689" fill="#000" font-size="14"> </text><text x="119.375" y="467.689" fill="#000" font-size="14" textLength="56.027">browsing</text></g><!--entity library--><g class="entity" data-qualified-name="wb.library" id="ent0004" data-source-line="78"><rect x="278.5" y="337.609" width="210.661" height="160.875" fill="#85BBF0" style="stroke:#78A8D8;stroke-width:0.5;"/><text x="305.588" y="364.219" fill="#000" font-size="16" textLength="54.242" font-weight="700">Library</text><text x="359.831" y="364.219" fill="#000" font-size="16" font-weight="700"> </text><text x="364.276" y="364.219" fill="#000" font-size="16" textLength="97.797" font-weight="700">Management</text><text x="309.147" y="380.191" fill="#000" font-size="12" textLength="54.68" font-style="italic">[ASP.NET</text><text x="363.827" y="380.191" fill="#000" font-size="12" font-style="italic"> </text><text x="367.161" y="380.191" fill="#000" font-size="12" textLength="26.666" font-style="italic">MVC</text><text x="393.827" y="380.191" fill="#000" font-size="12" font-style="italic"> </text><text x="397.161" y="380.191" fill="#000" font-size="12" textLength="61.354" font-style="italic">Controllers]</text><text x="381.886" y="397.361" fill="#000" font-size="14"> </text><text x="293.948" y="414.971" fill="#000" font-size="14" textLength="57.593">Manages</text><text x="351.541" y="414.971" fill="#000" font-size="14"> </text><text x="355.431" y="414.971" fill="#000" font-Line truncated
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" data-diagram-type="DESCRIPTION" style="width:1697px;height:1281px;background:#FFFFFF;" width="1697px" height="1281px" viewBox="0 0 1697 1281" zoomAndPan="magnify" preserveAspectRatio="none" contentStyleType="text/css"><?plantuml 1.2026.7?><defs/><g font-family="sans-serif" lengthAdjust="spacing"><g class="title" data-source-line="4"><text x="649.188" y="24.533" fill="#000" font-size="14" textLength="392.021" font-weight="700">Component diagram for Lumina Web Application Client 2.1</text></g><!--cluster wb--><g class="cluster" data-qualified-name="wb" id="ent0002" data-source-line="1666"><rect x="7" y="45.609" width="1468" height="769" fill="none" style="stroke:#444;stroke-width:1;stroke-dasharray:7,7;"/><text x="664.992" y="64.219" fill="#444" font-size="16" textLength="152.016" font-weight="700">Web Application 2.1</text><text x="709.998" y="80.191" fill="#444" font-size="12" textLength="62.004" font-weight="700">[container]</text></g><!--entity fileSystem--><g class="entity" data-qualified-name="wb.fileSystem" id="ent0003" data-source-line="78"><rect x="23" y="416.609" width="219.992" height="125.656" fill="#85BBF0" style="stroke:#78A8D8;stroke-width:0.5;"/><text x="37.41" y="443.219" fill="#000" font-size="16" textLength="27.563" font-weight="700">File</text><text x="64.973" y="443.219" fill="#000" font-size="16" font-weight="700"> </text><text x="69.418" y="443.219" fill="#000" font-size="16" textLength="56.922" font-weight="700">System</text><text x="126.34" y="443.219" fill="#000" font-size="16" font-weight="700"> </text><text x="130.785" y="443.219" fill="#000" font-size="16" textLength="97.797" font-weight="700">Management</text><text x="58.313" y="459.191" fill="#000" font-size="12" textLength="54.68" font-style="italic">[ASP.NET</text><text x="112.992" y="459.191" fill="#000" font-size="12" font-style="italic"> </text><text x="116.326" y="459.191" fill="#000" font-size="12" textLength="26.666" font-style="italic">MVC</text><text x="142.992" y="459.191" fill="#000" font-size="12" font-style="italic"> </text><text x="146.326" y="459.191" fill="#000" font-size="12" textLength="61.354" font-style="italic">Controllers]</text><text x="131.051" y="476.361" fill="#000" font-size="14"> </text><text x="37.672" y="493.971" fill="#000" font-size="14" textLength="51.365">Handles</text><text x="89.038" y="493.971" fill="#000" font-size="14"> </text><text x="92.927" y="493.971" fill="#000" font-size="14" textLength="17.896">file</text><text x="110.824" y="493.971" fill="#000" font-size="14"> </text><text x="114.713" y="493.971" fill="#000" font-size="14" textLength="44.338">system</text><text x="159.051" y="493.971" fill="#000" font-size="14"> </text><text x="162.941" y="493.971" fill="#000" font-size="14" textLength="65.379">operations</text><text x="33" y="511.58" fill="#000" font-size="14" textLength="55.262">including</text><text x="88.262" y="511.58" fill="#000" font-size="14"> </text><text x="92.151" y="511.58" fill="#000" font-size="14" textLength="41.234">drives,</text><text x="133.386" y="511.58" fill="#000" font-size="14"> </text><text x="137.275" y="511.58" fill="#000" font-size="14" textLength="68.469">directories,</text><text x="205.744" y="511.58" fill="#000" font-size="14"> </text><text x="209.634" y="511.58" fill="#000" font-size="14" textLength="23.358">and</text><text x="90.589" y="529.189" fill="#000" font-size="14" textLength="24.896">files</text><text x="115.486" y="529.189" fill="#000" font-size="14"> </text><text x="119.375" y="529.189" fill="#000" font-size="14" textLength="56.027">browsing</text></g><!--entity library--><g class="entity" data-qualified-name="wb.library" id="ent0004" data-source-line="78"><rect x="278.5" y="399.109" width="210.661" height="160.875" fill="#85BBF0" style="stroke:#78A8D8;stroke-width:0.5;"/><text x="305.588" y="425.719" fill="#000" font-size="16" textLength="54.242" font-weight="700">Library</text><text x="359.831" y="425.719" fill="#000" font-size="16" font-weight="700"> </text><text x="364.276" y="425.719" fill="#000" font-size="16" textLength="97.797" font-weight="700">Management</text><text x="309.147" y="441.691" fill="#000" font-size="12" textLength="54.68" font-style="italic">[ASP.NET</text><text x="363.827" y="441.691" fill="#000" font-size="12" font-style="italic"> </text><text x="367.161" y="441.691" fill="#000" font-size="12" textLength="26.666" font-style="italic">MVC</text><text x="393.827" y="441.691" fill="#000" font-size="12" font-style="italic"> </text><text x="397.161" y="441.691" fill="#000" font-size="12" textLength="61.354" font-style="italic">Controllers]</text><text x="381.886" y="458.861" fill="#000" font-size="14"> </text><text x="293.948" y="476.471" fill="#000" font-size="14" textLength="57.593">Manages</text><text x="351.541" y="476.471" fill="#000" font-size="14"> </text><text x="355.431" y="476.471" fill="#000" fontLine truncated

Before

Width:  |  Height:  |  Size: 36 KiB

After

Width:  |  Height:  |  Size: 46 KiB

@@ -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)
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" data-diagram-type="DESCRIPTION" style="width:1398px;height:1604px;background:#FFFFFF;" width="1398px" height="1604px" viewBox="0 0 1398 1604" zoomAndPan="magnify" preserveAspectRatio="none" contentStyleType="text/css"><?plantuml 1.2026.7?><defs/><g font-family="sans-serif" lengthAdjust="spacing"><g class="title" data-source-line="4"><text x="540.664" y="24.533" fill="#000" font-size="14" textLength="310.399" font-weight="700">Component diagram for Lumina API Server 2.2</text></g><!--cluster api--><g class="cluster" data-qualified-name="api" id="ent0002" data-source-line="1666"><rect x="7" y="269.609" width="957" height="862" fill="none" style="stroke:#444;stroke-width:1;stroke-dasharray:7,7;"/><text x="431.688" y="288.219" fill="#444" font-size="16" textLength="107.625" font-weight="700">API Server 2.2</text><text x="454.498" y="304.191" fill="#444" font-size="12" textLength="62.004" font-weight="700">[container]</text></g><!--entity endpoints--><g class="entity" data-qualified-name="api.endpoints" id="ent0003" data-source-line="78"><rect x="257.5" y="351.109" width="206.758" height="125.656" fill="#85BBF0" style="stroke:#78A8D8;stroke-width:0.5;"/><text x="306.215" y="377.719" fill="#000" font-size="16" textLength="26.672" font-weight="700">API</text><text x="332.887" y="377.719" fill="#000" font-size="16" font-weight="700"> </text><text x="337.332" y="377.719" fill="#000" font-size="16" textLength="78.211" font-weight="700">Endpoints</text><text x="319.189" y="393.691" fill="#000" font-size="12" textLength="83.379" font-style="italic">[FastEndpoints]</text><text x="358.934" y="410.861" fill="#000" font-size="14"> </text><text x="267.5" y="428.471" fill="#000" font-size="14" textLength="54.469">Provides</text><text x="321.969" y="428.471" fill="#000" font-size="14"> </text><text x="325.858" y="428.471" fill="#000" font-size="14" textLength="37.338">REST</text><text x="363.196" y="428.471" fill="#000" font-size="14"> </text><text x="367.086" y="428.471" fill="#000" font-size="14" textLength="22.565">API</text><text x="389.651" y="428.471" fill="#000" font-size="14"> </text><text x="393.541" y="428.471" fill="#000" font-size="14" textLength="60.717">endpoints</text><text x="275.272" y="446.08" fill="#000" font-size="14" textLength="16.338">for</text><text x="291.61" y="446.08" fill="#000" font-size="14"> </text><text x="295.5" y="446.08" fill="#000" font-size="14" textLength="38.131">media</text><text x="333.631" y="446.08" fill="#000" font-size="14"> </text><text x="337.521" y="446.08" fill="#000" font-size="14" textLength="81.717">management</text><text x="419.237" y="446.08" fill="#000" font-size="14"> </text><text x="423.127" y="446.08" fill="#000" font-size="14" textLength="23.358">and</text><text x="330.145" y="463.689" fill="#000" font-size="14" textLength="61.469">streaming</text></g><!--entity mediaManagement--><g class="entity" data-qualified-name="api.mediaManagement" id="ent0004" data-source-line="78"><rect x="504.5" y="624.109" width="174.889" height="145.781" fill="#85BBF0" style="stroke:#78A8D8;stroke-width:0.5;"/><text x="539.929" y="650.719" fill="#000" font-size="16" textLength="45.344" font-weight="700">Media</text><text x="585.272" y="650.719" fill="#000" font-size="16" font-weight="700"> </text><text x="589.718" y="650.719" fill="#000" font-size="16" textLength="54.242" font-weight="700">Library</text><text x="543.046" y="670.844" fill="#000" font-size="16" textLength="97.797" font-weight="700">Management</text><text x="543.262" y="686.816" fill="#000" font-size="12" textLength="44.684" font-style="italic">[Domain</text><text x="587.945" y="686.816" fill="#000" font-size="12" font-style="italic"> </text><text x="591.279" y="686.816" fill="#000" font-size="12" textLength="49.348" font-style="italic">Services]</text><text x="590" y="703.986" fill="#000" font-size="14"> </text><text x="518.8" y="721.596" fill="#000" font-size="14" textLength="51.365">Handles</text><text x="570.165" y="721.596" fill="#000" font-size="14"> </text><text x="574.055" y="721.596" fill="#000" font-size="14" textLength="38.131">media</text><text x="612.186" y="721.596" fill="#000" font-size="14"> </text><text x="616.075" y="721.596" fill="#000" font-size="14" textLength="49.014">libraries</text><text x="514.5" y="739.205" fill="#000" font-size="14" textLength="65.379">operations</text><text x="579.879" y="739.205" fill="#000" font-size="14"> </text><text x="583.769" y="739.205" fill="#000" font-size="14" textLength="23.358">and</text><text x="607.127" y="739.205" fill="#000" font-size="14"> </text><text x="611.017" y="739.205" fill="#000" font-size="14" textLength="58.372">metadata</text><text x="551.086" y="756.814" fill="#000" font-size="14" textLength="81.717">management</text></g><!--entity userManagement--><g class="entity" data-qualified-name="api.userManagement" id="ent0005" data-source-line="78">Line truncated
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" data-diagram-type="DESCRIPTION" style="width:1223px;height:2192px;background:#FFFFFF;" width="1223px" height="2192px" viewBox="0 0 1223 2192" zoomAndPan="magnify" preserveAspectRatio="none" contentStyleType="text/css"><?plantuml 1.2026.7?><defs/><g font-family="sans-serif" lengthAdjust="spacing"><g class="title" data-source-line="4"><text x="453.259" y="24.533" fill="#000" font-size="14" textLength="310.399" font-weight="700">Component diagram for Lumina API Server 2.2</text></g><!--cluster api--><g class="cluster" data-qualified-name="api" id="ent0002" data-source-line="1666"><rect x="25.19" y="269.609" width="780" height="1444.5" fill="none" style="stroke:#444;stroke-width:1;stroke-dasharray:7,7;"/><text x="361.378" y="288.219" fill="#444" font-size="16" textLength="107.625" font-weight="700">API Server 2.2</text><text x="384.188" y="304.191" fill="#444" font-size="12" textLength="62.004" font-weight="700">[container]</text></g><!--entity endpoints--><g class="entity" data-qualified-name="api.endpoints" id="ent0003" data-source-line="78"><rect x="163.69" y="323.609" width="206.758" height="125.656" fill="#85BBF0" style="stroke:#78A8D8;stroke-width:0.5;"/><text x="212.405" y="350.219" fill="#000" font-size="16" textLength="26.672" font-weight="700">API</text><text x="239.077" y="350.219" fill="#000" font-size="16" font-weight="700"> </text><text x="243.522" y="350.219" fill="#000" font-size="16" textLength="78.211" font-weight="700">Endpoints</text><text x="225.379" y="366.191" fill="#000" font-size="12" textLength="83.379" font-style="italic">[FastEndpoints]</text><text x="265.124" y="383.361" fill="#000" font-size="14"> </text><text x="173.69" y="400.971" fill="#000" font-size="14" textLength="54.469">Provides</text><text x="228.159" y="400.971" fill="#000" font-size="14"> </text><text x="232.048" y="400.971" fill="#000" font-size="14" textLength="37.338">REST</text><text x="269.386" y="400.971" fill="#000" font-size="14"> </text><text x="273.276" y="400.971" fill="#000" font-size="14" textLength="22.565">API</text><text x="295.841" y="400.971" fill="#000" font-size="14"> </text><text x="299.731" y="400.971" fill="#000" font-size="14" textLength="60.717">endpoints</text><text x="181.462" y="418.58" fill="#000" font-size="14" textLength="16.338">for</text><text x="197.8" y="418.58" fill="#000" font-size="14"> </text><text x="201.69" y="418.58" fill="#000" font-size="14" textLength="38.131">media</text><text x="239.821" y="418.58" fill="#000" font-size="14"> </text><text x="243.711" y="418.58" fill="#000" font-size="14" textLength="81.717">management</text><text x="325.427" y="418.58" fill="#000" font-size="14"> </text><text x="329.317" y="418.58" fill="#000" font-size="14" textLength="23.358">and</text><text x="236.335" y="436.189" fill="#000" font-size="14" textLength="61.469">streaming</text></g><!--entity mediaManagement--><g class="entity" data-qualified-name="api.mediaManagement" id="ent0004" data-source-line="78"><rect x="317.69" y="1340.609" width="174.889" height="145.781" fill="#85BBF0" style="stroke:#78A8D8;stroke-width:0.5;"/><text x="353.119" y="1367.219" fill="#000" font-size="16" textLength="45.344" font-weight="700">Media</text><text x="398.462" y="1367.219" fill="#000" font-size="16" font-weight="700"> </text><text x="402.908" y="1367.219" fill="#000" font-size="16" textLength="54.242" font-weight="700">Library</text><text x="356.236" y="1387.344" fill="#000" font-size="16" textLength="97.797" font-weight="700">Management</text><text x="356.452" y="1403.316" fill="#000" font-size="12" textLength="44.684" font-style="italic">[Domain</text><text x="401.135" y="1403.316" fill="#000" font-size="12" font-style="italic"> </text><text x="404.469" y="1403.316" fill="#000" font-size="12" textLength="49.348" font-style="italic">Services]</text><text x="403.19" y="1420.486" fill="#000" font-size="14"> </text><text x="331.99" y="1438.096" fill="#000" font-size="14" textLength="51.365">Handles</text><text x="383.355" y="1438.096" fill="#000" font-size="14"> </text><text x="387.245" y="1438.096" fill="#000" font-size="14" textLength="38.131">media</text><text x="425.376" y="1438.096" fill="#000" font-size="14"> </text><text x="429.265" y="1438.096" fill="#000" font-size="14" textLength="49.014">libraries</text><text x="327.69" y="1455.705" fill="#000" font-size="14" textLength="65.379">operations</text><text x="393.069" y="1455.705" fill="#000" font-size="14"> </text><text x="396.959" y="1455.705" fill="#000" font-size="14" textLength="23.358">and</text><text x="420.317" y="1455.705" fill="#000" font-size="14"> </text><text x="424.207" y="1455.705" fill="#000" font-size="14" textLength="58.372">metadata</text><text x="364.276" y="1473.314" fill="#000" font-size="14" textLength="81.717">management</text></g><!--entity userManagement--><g class="entity" data-qualified-name="api.userManagement" Line truncated

Before

Width:  |  Height:  |  Size: 52 KiB

After

Width:  |  Height:  |  Size: 65 KiB

@@ -0,0 +1,442 @@
@startuml Scheduled Jobs Code
!include <C4/C4_Component>
LAYOUT_WITH_LEGEND()
title Code diagram for Scheduled Jobs 3.2.3
skinparam class {
BackgroundColor White
BorderColor Black
}
' ============================== DOMAIN AGGREGATE ==============================
class ScheduledJob {
- _currentExecutionRunId: Optional<Guid>
+ Name: string
+ TaskType: ScheduledTaskType
+ Schedule: Schedule
+ Status: ScheduledJobStatus
+ OwnerUserId: UserId
+ LastStartedOnUtc: Optional<DateTime>
+ LastCompletedOnUtc: Optional<DateTime>
+ {static} 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>
}
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<IntervalSchedule>
}
class DailySchedule {
+ Hour: int
+ Minute: int
+ {static} Create(hour: int, minute: int): Result<DailySchedule>
}
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<ScheduledJobResponse>, token: CancellationToken): Task
+ SendScheduledJobExecutionStartedAsync(execution: ScheduledJobExecutionResponse, token: CancellationToken): Task
+ SendScheduledJobExecutionCompletedAsync(execution: ScheduledJobExecutionResponse, token: CancellationToken): Task
}
interface IScheduledJobRepository {
+ GetByIdAsync(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>>
}
interface IScheduledJobExecutionRepository {
+ GetByIdAsync(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>>
}
' ============================== APPLICATION HANDLERS ==============================
class AddScheduledJobCommandHandler {
+ HandleAsync(command: AddScheduledJobCommand, token: CancellationToken): Task<Result<ScheduledJobResponse>>
}
class StartScheduledJobCommandHandler {
+ HandleAsync(command: StartScheduledJobCommand, token: CancellationToken): Task<Result<ScheduledJobResponse>>
}
class StopScheduledJobCommandHandler {
+ HandleAsync(command: StopScheduledJobCommand, token: CancellationToken): Task<Result<ScheduledJobResponse>>
}
class FireScheduledJobCommandHandler {
+ HandleAsync(command: FireScheduledJobCommand, token: CancellationToken): Task<Result<ScheduledJobResponse>>
}
class RemoveScheduledJobCommandHandler {
+ HandleAsync(command: RemoveScheduledJobCommand, token: CancellationToken): Task<Result<Success>>
}
class GetScheduledJobsQueryHandler {
+ HandleAsync(query: GetScheduledJobsQuery, token: CancellationToken): Task<Result<IEnumerable<ScheduledJobResponse>>>
}
class GetScheduledJobHistoryQueryHandler {
+ HandleAsync(query: GetScheduledJobHistoryQuery, token: CancellationToken): Task<Result<IEnumerable<ScheduledJobExecutionResponse>>>
}
' ============================== 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<ScheduledJobId, ScheduledJobRuntimeState>
}
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<Result<Success>>
}
class MediaLibraryScanTaskExecutor {
- _unitOfWork: IUnitOfWork
- _domainEventPublisher: IDomainEventPublisher
+ ExecutePayloadAsync(scheduledJob: ScheduledJob, token: CancellationToken): Task<Result<Success>>
}
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<Result<Success>>
}
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<ScheduledJobsHub, IScheduledJobsClient>
+ SendScheduledJobsAsync(scheduledJobs: IReadOnlyList<ScheduledJobResponse>, 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<ScheduledJobResponse>): 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
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" data-diagram-type="CLASS" style="width:6534px;height:3023px;background:#FFFFFF;" width="6534px" height="3023px" viewBox="0 0 6534 3023" zoomAndPan="magnify" preserveAspectRatio="none" contentStyleType="text/css"><?plantuml 1.2026.7?><defs/><g font-family="sans-serif" lengthAdjust="spacing"><g class="title" data-source-line="4"><text x="3132.555" y="24.533" fill="#000" font-size="14" textLength="262.179" font-weight="700">Code diagram for Scheduled Jobs 3.2.3</text></g><!--class ScheduledJob--><g class="entity" data-qualified-name="ScheduledJob" id="ent0001" data-source-line="13"><rect x="2808" y="1456.609" width="265.647" height="470.625" fill="#FFF" style="stroke:#000;stroke-width:0.5;" rx="2.5" ry="2.5"/><ellipse cx="2892.205" cy="1472.609" rx="11" ry="11" fill="#ADD1B2" style="stroke:#181818;stroke-width:1;"/><path d="M2894.971,1468.484 Q2895.127,1468.266 2895.314,1468.156 Q2895.502,1468.047 2895.721,1468.047 Q2896.096,1468.047 2896.33,1468.313 Q2896.564,1468.563 2896.564,1469.172 L2896.564,1470.625 Q2896.564,1471.234 2896.33,1471.5 Q2896.096,1471.766 2895.721,1471.766 Q2895.377,1471.766 2895.174,1471.563 Q2894.971,1471.375 2894.861,1470.859 Q2894.814,1470.5 2894.627,1470.313 Q2894.299,1469.938 2893.689,1469.719 Q2893.08,1469.5 2892.455,1469.5 Q2891.689,1469.5 2891.049,1469.828 Q2890.424,1470.156 2889.924,1470.906 Q2889.439,1471.656 2889.439,1472.688 L2889.439,1473.781 Q2889.439,1475.016 2890.33,1475.844 Q2891.221,1476.656 2892.814,1476.656 Q2893.752,1476.656 2894.408,1476.406 Q2894.799,1476.25 2895.221,1475.813 Q2895.486,1475.547 2895.627,1475.469 Q2895.783,1475.391 2895.986,1475.391 Q2896.314,1475.391 2896.564,1475.656 Q2896.83,1475.906 2896.83,1476.25 Q2896.83,1476.594 2896.486,1477 Q2895.986,1477.578 2895.189,1477.906 Q2894.111,1478.359 2892.814,1478.359 Q2891.299,1478.359 2890.096,1477.734 Q2889.111,1477.234 2888.424,1476.172 Q2887.736,1475.094 2887.736,1473.813 L2887.736,1472.656 Q2887.736,1471.328 2888.346,1470.188 Q2888.971,1469.031 2890.064,1468.422 Q2891.158,1467.797 2892.393,1467.797 Q2893.127,1467.797 2893.768,1467.969 Q2894.424,1468.125 2894.971,1468.484 Z " fill="#000"/><text x="2912.705" y="1478.338" fill="#000" font-size="14" textLength="88.737">ScheduledJob</text><line x1="2809" y1="1488.609" x2="3072.647" y2="1488.609" style="stroke:#000;stroke-width:0.5;"/><g data-visibility-modifier="PRIVATE_FIELD"><rect x="2816" y="1508.719" width="6" height="6" fill="none" style="stroke:#C82930;stroke-width:1;"/></g><text x="2828" y="1507.143" fill="#000" font-size="14" textLength="154.089">_currentExecutionRunId:</text><text x="2828" y="1524.752" fill="#000" font-size="14" textLength="98.068">Optional&lt;Guid></text><g data-visibility-modifier="PUBLIC_FIELD"><ellipse cx="2819" cy="1538.133" rx="3" ry="3" fill="none" style="stroke:#038048;stroke-width:1;"/></g><text x="2828" y="1542.361" fill="#000" font-size="14" textLength="41.234">Name:</text><text x="2869.234" y="1542.361" fill="#000" font-size="14"> </text><text x="2873.124" y="1542.361" fill="#000" font-size="14" textLength="34.234">string</text><g data-visibility-modifier="PUBLIC_FIELD"><ellipse cx="2819" cy="1555.742" rx="3" ry="3" fill="none" style="stroke:#038048;stroke-width:1;"/></g><text x="2828" y="1559.971" fill="#000" font-size="14" textLength="65.352">TaskType:</text><text x="2893.352" y="1559.971" fill="#000" font-size="14"> </text><text x="2897.241" y="1559.971" fill="#000" font-size="14" textLength="127.627">ScheduledTaskType</text><g data-visibility-modifier="PUBLIC_FIELD"><ellipse cx="2819" cy="1573.352" rx="3" ry="3" fill="none" style="stroke:#038048;stroke-width:1;"/></g><text x="2828" y="1577.58" fill="#000" font-size="14" textLength="62.269">Schedule:</text><text x="2890.269" y="1577.58" fill="#000" font-size="14"> </text><text x="2894.158" y="1577.58" fill="#000" font-size="14" textLength="58.379">Schedule</text><g data-visibility-modifier="PUBLIC_FIELD"><ellipse cx="2819" cy="1590.961" rx="3" ry="3" fill="none" style="stroke:#038048;stroke-width:1;"/></g><text x="2828" y="1595.189" fill="#000" font-size="14" textLength="43.579">Status:</text><text x="2871.579" y="1595.189" fill="#000" font-size="14"> </text><text x="2875.469" y="1595.189" fill="#000" font-size="14" textLength="128.427">ScheduledJobStatus</text><g data-visibility-modifier="PUBLIC_FIELD"><ellipse cx="2819" cy="1608.57" rx="3" ry="3" fill="none" style="stroke:#038048;stroke-width:1;"/></g><text x="2828" y="1612.799" fill="#000" font-size="14" textLength="86.358">OwnerUserId:</text><text x="2914.358" y="1612.799" fill="#000" font-size="14"> </text><text x="2918.248" y="1612.799" fill="#000" font-size="14" textLength="41.234">UserId</text><g data-visibility-modifier="PUBLIC_FIELD"><ellipse cx="2819" cy="1634.984" rx="3" ry="3" fill="none" style="stroke:#038048;stroke-width:1;"/></g><text x="2828" y="1630.408" fill="#000" font-size="14" textLength="115.165">LaLine truncated

After

Width:  |  Height:  |  Size: 271 KiB

@@ -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
}
@@ -0,0 +1,2 @@
PUT {{host}}/api/v1/scheduled-jobs/{{$guid}}/fire
Authorization: Bearer {{ACCESS_TOKEN}}
@@ -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}}
@@ -0,0 +1,2 @@
GET {{host}}/api/v1/scheduled-jobs
Authorization: Bearer {{ACCESS_TOKEN}}
@@ -0,0 +1,2 @@
GET {{host}}/api/v1/scheduled-jobs/display-preferences
Authorization: Bearer {{ACCESS_TOKEN}}
@@ -0,0 +1,2 @@
DELETE {{host}}/api/v1/scheduled-jobs/{{$guid}}
Authorization: Bearer {{ACCESS_TOKEN}}
@@ -0,0 +1,2 @@
PUT {{host}}/api/v1/scheduled-jobs/{{$guid}}/start
Authorization: Bearer {{ACCESS_TOKEN}}
@@ -0,0 +1,2 @@
PUT {{host}}/api/v1/scheduled-jobs/{{$guid}}/stop
Authorization: Bearer {{ACCESS_TOKEN}}
@@ -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"
}
@@ -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;
/// <summary>
/// Repository entity for a scheduled job.
/// </summary>
[DebuggerDisplay("Id: {Id}, Status: {Status}")]
public class ScheduledJobEntity : IStorageEntity, IAuditableEntity
{
/// <summary>
/// Gets the Id of the scheduled job.
/// </summary>
public required Guid Id { get; init; }
/// <summary>
/// Gets the name of the scheduled job.
/// </summary>
public required string Name { get; init; }
/// <summary>
/// Gets the type of the task executed by the scheduled job.
/// </summary>
public required ScheduledTaskType TaskType { get; init; }
/// <summary>
/// Gets the type of the schedule of the scheduled job.
/// </summary>
public required ScheduleType ScheduleType { get; init; }
/// <summary>
/// Gets the interval in minutes of the schedule of the scheduled job, when its <see cref="ScheduleType"/> is <see cref="ScheduleType.WithIntervalInMinutes"/>.
/// </summary>
public int? IntervalMinutes { get; init; }
/// <summary>
/// Gets the hour of the schedule of the scheduled job, when its <see cref="ScheduleType"/> is <see cref="ScheduleType.DailyAtHourAndMinute"/>.
/// </summary>
public int? Hour { get; init; }
/// <summary>
/// Gets the minute of the schedule of the scheduled job, when its <see cref="ScheduleType"/> is <see cref="ScheduleType.DailyAtHourAndMinute"/>.
/// </summary>
public int? Minute { get; init; }
/// <summary>
/// Gets the status of the scheduled job.
/// </summary>
public required ScheduledJobStatus Status { get; init; }
/// <summary>
/// Gets the Id of the user that owns the scheduled job.
/// </summary>
public required Guid OwnerUserId { get; init; }
/// <summary>
/// Gets the optional date and time when the task of the scheduled job last started its execution.
/// </summary>
public DateTime? LastStartedOnUtc { get; init; }
/// <summary>
/// Gets the optional date and time when the task of the scheduled job last completed its execution.
/// </summary>
public DateTime? LastCompletedOnUtc { get; init; }
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
public required DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the Id of the user that created the entity.
/// </summary>
public required Guid CreatedBy { get; set; }
/// <summary>
/// Gets or sets the optional time and date when the entity was updated.
/// </summary>
public DateTime? UpdatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the optional Id of the user that updated the entity.
/// </summary>
public required Guid? UpdatedBy { get; set; }
}
@@ -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;
/// <summary>
/// Repository entity for an execution of the task of a scheduled job.
/// </summary>
[DebuggerDisplay("Id: {Id}, ScheduledJobId: {ScheduledJobId}")]
public class ScheduledJobExecutionEntity : IStorageEntity, IAuditableEntity
{
/// <summary>
/// Gets the Id of the execution of the task of a scheduled job.
/// </summary>
public required Guid Id { get; init; }
/// <summary>
/// Gets the Id of the scheduled job whose task was executed.
/// </summary>
public required Guid ScheduledJobId { get; init; }
/// <summary>
/// Gets the type of the task that was executed.
/// </summary>
public required ScheduledTaskType TaskType { get; init; }
/// <summary>
/// Gets a value indicating whether the execution was triggered by the execution cycle of the scheduled job, or it was a one time execution.
/// </summary>
public required bool IsCycleRun { get; init; }
/// <summary>
/// Gets the date and time when the execution started.
/// </summary>
public required DateTime StartedOnUtc { get; init; }
/// <summary>
/// Gets the optional date and time when the execution completed.
/// </summary>
public DateTime? CompletedOnUtc { get; init; }
/// <summary>
/// Gets a value indicating whether the execution cycle of the scheduled job was active when the execution started.
/// </summary>
/// <remarks>
/// 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 <see cref="IsCycleRun"/>, which records how the execution was triggered for the audit trail.
/// </remarks>
public required bool WasCycleActive { get; init; }
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
public required DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the Id of the user that created the entity.
/// </summary>
public required Guid CreatedBy { get; set; }
/// <summary>
/// Gets or sets the optional time and date when the entity was updated.
/// </summary>
public DateTime? UpdatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the optional Id of the user that updated the entity.
/// </summary>
public required Guid? UpdatedBy { get; set; }
}
@@ -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;
/// <summary>
/// Repository entity for the display preferences of the scheduler page of a user.
/// </summary>
[DebuggerDisplay("UserId: {UserId}, DisplayTimeSpan: {DisplayTimeSpan}")]
public class SchedulerDisplayPreferencesEntity : IStorageEntity, IAuditableEntity
{
/// <summary>
/// Gets or sets the Id of the display preferences.
/// </summary>
public required Guid Id { get; init; }
/// <summary>
/// Gets or sets the Id of the user that owns the display preferences.
/// </summary>
public required Guid UserId { get; set; }
/// <summary>
/// Gets or sets the type of the scheduled job tasks whose executions are shown on the scheduler page, or <see langword="null"/> when all of them are shown.
/// </summary>
public ScheduledTaskType? JobTypeFilter { get; set; }
/// <summary>
/// Gets or sets the time span, expressed in <see cref="DisplayTimeUnit"/>, that the scheduler page shows.
/// </summary>
public required int DisplayTimeSpan { get; set; }
/// <summary>
/// Gets or sets the unit in which the displayed time span of the scheduler page is expressed.
/// </summary>
public required SchedulerDisplayTimeUnit DisplayTimeUnit { get; set; }
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
public required DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the Id of the user that created the entity.
/// </summary>
public required Guid CreatedBy { get; set; }
/// <summary>
/// Gets or sets the optional time and date when the entity was updated.
/// </summary>
public DateTime? UpdatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the optional Id of the user that updated the entity.
/// </summary>
public required Guid? UpdatedBy { get; set; }
}
@@ -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;
/// <summary>
/// Interface for the repository for the executions of the tasks of scheduled jobs.
/// </summary>
public interface IScheduledJobExecutionRepository : IRepository<ScheduledJobExecutionEntity>,
IGetByIdRepositoryAction<ScheduledJobExecutionEntity, Guid>,
IInsertRepositoryAction<ScheduledJobExecutionEntity>,
IUpdateRepositoryAction<ScheduledJobExecutionEntity>
{
/// <summary>
/// Gets the most recent execution of the task of a scheduled job identified by <paramref name="scheduledJobId"/> that is still running, from the storage medium.
/// </summary>
/// <param name="scheduledJobId">The Id of the scheduled job whose running execution is retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the running execution of the scheduled job, or <see langword="null"/>.</returns>
Task<Result<ScheduledJobExecutionEntity?>> GetOpenByScheduledJobIdAsync(Guid scheduledJobId, CancellationToken cancellationToken);
/// <summary>
/// Gets the executions of the tasks of scheduled jobs that started in the interval between <paramref name="fromUtc"/> and <paramref name="toUtc"/>, from the storage medium.
/// </summary>
/// <param name="fromUtc">The inclusive lower bound of the interval, in UTC.</param>
/// <param name="toUtc">The inclusive upper bound of the interval, in UTC.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="ScheduledJobExecutionEntity"/>, or an error.</returns>
Task<Result<IEnumerable<ScheduledJobExecutionEntity>>> GetByTimeRangeAsync(DateTime fromUtc, DateTime toUtc, CancellationToken cancellationToken);
/// <summary>
/// Removes all the executions of the task of a scheduled job identified by <paramref name="scheduledJobId"/>, from the storage medium.
/// </summary>
/// <param name="scheduledJobId">The Id of the scheduled job whose executions are removed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Success>> DeleteByScheduledJobIdAsync(Guid scheduledJobId, CancellationToken cancellationToken);
/// <summary>
/// Removes all the executions of the tasks of scheduled jobs that started before <paramref name="cutoffUtc"/>, from the storage medium.
/// </summary>
/// <param name="cutoffUtc">The exclusive lower bound of the retained interval, in UTC; executions that started before it are removed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Success>> DeleteOlderThanAsync(DateTime cutoffUtc, CancellationToken cancellationToken);
}
@@ -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;
/// <summary>
/// Interface for the repository for scheduled jobs.
/// </summary>
public interface IScheduledJobRepository : IRepository<ScheduledJobEntity>,
IGetByIdRepositoryAction<ScheduledJobEntity, Guid>,
IGetAllRepositoryAction<ScheduledJobEntity>,
IInsertRepositoryAction<ScheduledJobEntity>,
IUpdateRepositoryAction<ScheduledJobEntity>,
IDeleteByIdRepositoryAction<Guid>
{
/// <summary>
/// Gets a scheduled job identified by <paramref name="id"/> from the storage medium, without tracking it.
/// </summary>
/// <param name="id">The id of the scheduled job to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="ScheduledJobEntity"/> identified by <paramref name="id"/>, or an error.</returns>
Task<Result<ScheduledJobEntity?>> GetByIdWithoutTrackingAsync(Guid id, CancellationToken cancellationToken);
/// <summary>
/// Gets the scheduled jobs that have an active or running execution cycle, from the storage medium.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="ScheduledJobEntity"/>, or an error.</returns>
Task<Result<IEnumerable<ScheduledJobEntity>>> GetActiveOrRunningAsync(CancellationToken cancellationToken);
}
@@ -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;
/// <summary>
/// Interface for the repository for the display preferences of the scheduler page.
/// </summary>
public interface ISchedulerDisplayPreferencesRepository : IRepository<SchedulerDisplayPreferencesEntity>
{
/// <summary>
/// Gets the display preferences of the scheduler page of the user identified by <paramref name="userId"/>, if they exist.
/// </summary>
/// <param name="userId">The Id of the user whose display preferences are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the display preferences of the user, or an error.</returns>
Task<Result<SchedulerDisplayPreferencesEntity?>> GetByUserIdAsync(Guid userId, CancellationToken cancellationToken);
/// <summary>
/// Inserts the display preferences of the scheduler page of a user, or updates them when they already exist.
/// </summary>
/// <param name="preferences">The display preferences to insert or update.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Updated>> UpsertAsync(SchedulerDisplayPreferencesEntity preferences, CancellationToken cancellationToken);
}
@@ -43,4 +43,12 @@ public interface IDataSeedService
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Created>> SetAdminRoleToAdministratorAccount(Guid userId, CancellationToken cancellationToken);
/// <summary>
/// Sets up the default scheduled jobs, owned by the administrator account.
/// </summary>
/// <param name="adminUserId">The unique identifier of the administrator account that owns the default scheduled jobs.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Created>> SetDefaultScheduledJobsAsync(Guid adminUserId, CancellationToken cancellationToken);
}
@@ -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
/// </summary>
ILibraryBookReaderConfigurationRepository LibraryBookReaderConfigurationRepository { get; }
/// <summary>
/// Gets the scheduled job repository.
/// </summary>
IScheduledJobRepository ScheduledJobRepository { get; }
/// <summary>
/// Gets the scheduled job execution repository.
/// </summary>
IScheduledJobExecutionRepository ScheduledJobExecutionRepository { get; }
/// <summary>
/// Gets the scheduler display preferences repository.
/// </summary>
ISchedulerDisplayPreferencesRepository SchedulerDisplayPreferencesRepository { get; }
/// <summary>
/// Gets the plugin repository.
/// </summary>
@@ -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;
/// <summary>
/// Interface for the service that schedules and executes the tasks of scheduled jobs.
/// </summary>
public interface IScheduledJobScheduler
{
/// <summary>
/// Starts the execution cycle of the scheduled job identified by <paramref name="scheduledJobId"/>.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose execution cycle is started.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
Task StartCycleAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken);
/// <summary>
/// Stops the execution cycle of the scheduled job identified by <paramref name="scheduledJobId"/>.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose execution cycle is stopped.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
Task StopCycleAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken);
/// <summary>
/// Fires the task of the scheduled job identified by <paramref name="scheduledJobId"/> once, without affecting its execution cycle.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose task is fired.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
Task RunOnceAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken);
}
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="AddScheduledJobRequest"/>.
/// </summary>
public static class AddScheduledJobRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="AddScheduledJobCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static AddScheduledJobCommand ToCommand(this AddScheduledJobRequest request)
{
return new AddScheduledJobCommand(
request.Name,
request.TaskType,
request.ScheduleType,
request.IntervalMinutes,
request.Hour,
request.Minute
);
}
}
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="FireScheduledJobRequest"/>.
/// </summary>
public static class FireScheduledJobRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="FireScheduledJobCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static FireScheduledJobCommand ToCommand(this FireScheduledJobRequest request)
{
return new FireScheduledJobCommand(
request.ScheduledJobId
);
}
}
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="GetScheduledJobHistoryRequest"/>.
/// </summary>
public static class GetScheduledJobHistoryRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="GetScheduledJobHistoryQuery"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted query.</returns>
public static GetScheduledJobHistoryQuery ToQuery(this GetScheduledJobHistoryRequest request)
{
return new GetScheduledJobHistoryQuery(
request.From,
request.To
);
}
}
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="RemoveScheduledJobRequest"/>.
/// </summary>
public static class RemoveScheduledJobRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="RemoveScheduledJobCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static RemoveScheduledJobCommand ToCommand(this RemoveScheduledJobRequest request)
{
return new RemoveScheduledJobCommand(
request.ScheduledJobId
);
}
}
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="ScheduledJobEntity"/>.
/// </summary>
public static class ScheduledJobEntityMapping
{
/// <summary>
/// Converts <paramref name="repositoryEntity"/> to <see cref="ScheduledJob"/>.
/// </summary>
/// <param name="repositoryEntity">The repository entity to be converted.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a converted <see cref="ScheduledJob"/>, or an error message.
/// </returns>
public static Result<ScheduledJob> ToDomainEntity(this ScheduledJobEntity repositoryEntity)
{
Result<Schedule> 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<DateTime>.FromNullable(repositoryEntity.LastStartedOnUtc),
Optional<DateTime>.FromNullable(repositoryEntity.LastCompletedOnUtc)
);
}
/// <summary>
/// Converts <paramref name="repositoryEntities"/> to a collection of <see cref="ScheduledJob"/>.
/// </summary>
/// <param name="repositoryEntities">The repository entities to be converted.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a collection of converted <see cref="ScheduledJob"/>, or an error message.
/// </returns>
public static IEnumerable<Result<ScheduledJob>> ToDomainEntities(this IEnumerable<ScheduledJobEntity> repositoryEntities)
{
return repositoryEntities.Select(repositoryEntity => repositoryEntity.ToDomainEntity());
}
/// <summary>
/// Converts <paramref name="repositoryEntity"/> to <see cref="ScheduledJobResponse"/>.
/// </summary>
/// <param name="repositoryEntity">The repository entity to be converted.</param>
/// <returns>The converted scheduled job response.</returns>
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
);
}
/// <summary>
/// Creates the schedule of <paramref name="repositoryEntity"/> from its flattened schedule properties.
/// </summary>
/// <param name="repositoryEntity">The repository entity whose schedule is created.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a created <see cref="Schedule"/>, or an error message.
/// </returns>
private static Result<Schedule> CreateSchedule(ScheduledJobEntity repositoryEntity)
{
if (repositoryEntity.ScheduleType == ScheduleType.WithIntervalInMinutes)
{
Result<IntervalSchedule> intervalScheduleResult = IntervalSchedule.Create(repositoryEntity.IntervalMinutes ?? 0);
if (intervalScheduleResult.IsFailure)
return intervalScheduleResult.Errors;
return Result.From<Schedule>(intervalScheduleResult.Value);
}
if (repositoryEntity.ScheduleType == ScheduleType.OnceAtStartup)
{
Result<OnceAtStartupSchedule> onceAtStartupScheduleResult = OnceAtStartupSchedule.Create();
if (onceAtStartupScheduleResult.IsFailure)
return onceAtStartupScheduleResult.Errors;
return Result.From<Schedule>(onceAtStartupScheduleResult.Value);
}
Result<DailySchedule> dailyScheduleResult = DailySchedule.Create(repositoryEntity.Hour ?? 0, repositoryEntity.Minute ?? 0);
if (dailyScheduleResult.IsFailure)
return dailyScheduleResult.Errors;
return Result.From<Schedule>(dailyScheduleResult.Value);
}
}
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="ScheduledJobExecutionEntity"/>.
/// </summary>
public static class ScheduledJobExecutionEntityMapping
{
/// <summary>
/// Converts <paramref name="repositoryEntity"/> to <see cref="ScheduledJobExecutionResponse"/>.
/// </summary>
/// <param name="repositoryEntity">The repository entity to be converted.</param>
/// <returns>The converted execution response.</returns>
public static ScheduledJobExecutionResponse ToResponse(this ScheduledJobExecutionEntity repositoryEntity)
{
return new ScheduledJobExecutionResponse(
repositoryEntity.Id,
repositoryEntity.ScheduledJobId,
repositoryEntity.TaskType,
repositoryEntity.IsCycleRun,
repositoryEntity.StartedOnUtc,
repositoryEntity.CompletedOnUtc
);
}
}
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="ScheduledJob"/>.
/// </summary>
public static class ScheduledJobMapping
{
/// <summary>
/// Converts <paramref name="domainEntity"/> to <see cref="ScheduledJobEntity"/>.
/// </summary>
/// <param name="domainEntity">The domain entity to be converted.</param>
/// <returns>The converted repository entity.</returns>
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
};
}
/// <summary>
/// Converts <paramref name="domainEntity"/> to <see cref="ScheduledJobResponse"/>.
/// </summary>
/// <param name="domainEntity">The domain entity to be converted.</param>
/// <returns>The converted scheduled job response.</returns>
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
);
}
/// <summary>
/// Gets the interval in minutes of the schedule of <paramref name="domainEntity"/>, when it is an interval schedule.
/// </summary>
/// <param name="domainEntity">The scheduled job whose schedule interval is retrieved.</param>
/// <returns>The interval in minutes of the schedule, or <see langword="null"/> when the schedule is not an interval schedule.</returns>
private static int? GetIntervalMinutes(ScheduledJob domainEntity)
{
return domainEntity.Schedule is IntervalSchedule intervalSchedule ? intervalSchedule.IntervalMinutes : null;
}
/// <summary>
/// Gets the hour of the schedule of <paramref name="domainEntity"/>, when it is a daily schedule.
/// </summary>
/// <param name="domainEntity">The scheduled job whose schedule hour is retrieved.</param>
/// <returns>The hour of the schedule, or <see langword="null"/> when the schedule is not a daily schedule.</returns>
private static int? GetHour(ScheduledJob domainEntity)
{
return domainEntity.Schedule is DailySchedule dailySchedule ? dailySchedule.Hour : null;
}
/// <summary>
/// Gets the minute of the schedule of <paramref name="domainEntity"/>, when it is a daily schedule.
/// </summary>
/// <param name="domainEntity">The scheduled job whose schedule minute is retrieved.</param>
/// <returns>The minute of the schedule, or <see langword="null"/> when the schedule is not a daily schedule.</returns>
private static int? GetMinute(ScheduledJob domainEntity)
{
return domainEntity.Schedule is DailySchedule dailySchedule ? dailySchedule.Minute : null;
}
}
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="SchedulerDisplayPreferencesEntity"/>.
/// </summary>
public static class SchedulerDisplayPreferencesEntityMapping
{
private const int DEFAULT_DISPLAY_TIME_SPAN = 10;
private const SchedulerDisplayTimeUnit DEFAULT_DISPLAY_TIME_UNIT = SchedulerDisplayTimeUnit.Minutes;
/// <summary>
/// Converts <paramref name="repositoryEntity"/> to <see cref="SchedulerDisplayPreferencesResponse"/>.
/// </summary>
/// <param name="repositoryEntity">The repository entity to be converted.</param>
/// <returns>The converted response.</returns>
public static SchedulerDisplayPreferencesResponse ToResponse(this SchedulerDisplayPreferencesEntity repositoryEntity)
{
return new SchedulerDisplayPreferencesResponse(
repositoryEntity.UserId,
repositoryEntity.JobTypeFilter,
repositoryEntity.DisplayTimeSpan,
repositoryEntity.DisplayTimeUnit
);
}
/// <summary>
/// Converts the lack of stored display preferences to the default <see cref="SchedulerDisplayPreferencesResponse"/> of the user identified by <paramref name="userId"/>.
/// </summary>
/// <param name="repositoryEntity">The missing repository entity, which is <see langword="null"/>.</param>
/// <param name="userId">The Id of the user that owns the display preferences.</param>
/// <returns>The converted response with the default display preferences.</returns>
public static SchedulerDisplayPreferencesResponse ToDefaultResponse(this SchedulerDisplayPreferencesEntity? repositoryEntity, Guid userId)
{
return new SchedulerDisplayPreferencesResponse(
userId,
null,
DEFAULT_DISPLAY_TIME_SPAN,
DEFAULT_DISPLAY_TIME_UNIT
);
}
}
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="StartScheduledJobRequest"/>.
/// </summary>
public static class StartScheduledJobRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="StartScheduledJobCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static StartScheduledJobCommand ToCommand(this StartScheduledJobRequest request)
{
return new StartScheduledJobCommand(
request.ScheduledJobId
);
}
}
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="StopScheduledJobRequest"/>.
/// </summary>
public static class StopScheduledJobRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="StopScheduledJobCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static StopScheduledJobCommand ToCommand(this StopScheduledJobRequest request)
{
return new StopScheduledJobCommand(
request.ScheduledJobId
);
}
}
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="UpdateSchedulerDisplayPreferencesRequest"/>.
/// </summary>
public static class UpdateSchedulerDisplayPreferencesRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="UpdateSchedulerDisplayPreferencesCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static UpdateSchedulerDisplayPreferencesCommand ToCommand(this UpdateSchedulerDisplayPreferencesRequest request)
{
return new UpdateSchedulerDisplayPreferencesCommand(
request.JobTypeFilter,
request.DisplayTimeSpan,
request.DisplayTimeUnit
);
}
}
@@ -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<SetupApplicationCo
private readonly IQRCodeGenerator _qRCodeGenerator;
private readonly IDateTimeProvider _dateTimeProvider;
private readonly IDataSeedService _dataSeedService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IValidator<SetupApplicationCommand> _validator;
/// <summary>
@@ -44,6 +50,7 @@ public class SetupApplicationCommandHandler : ICommandHandler<SetupApplicationCo
/// <param name="qRCodeGenerator">Injected service for generating QR codes.</param>
/// <param name="dateTimeProvider">Injected service for time related concerns.</param>
/// <param name="dataSeedService">Injected service for the initial persistence medium data seed.</param>
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public SetupApplicationCommandHandler(
IUnitOfWork unitOfWork,
@@ -53,6 +60,7 @@ public class SetupApplicationCommandHandler : ICommandHandler<SetupApplicationCo
IQRCodeGenerator qRCodeGenerator,
IDateTimeProvider dateTimeProvider,
IDataSeedService dataSeedService,
IDomainEventsQueue domainEventsQueue,
IValidator<SetupApplicationCommand> validator)
{
_unitOfWork = unitOfWork;
@@ -62,6 +70,7 @@ public class SetupApplicationCommandHandler : ICommandHandler<SetupApplicationCo
_qRCodeGenerator = qRCodeGenerator;
_dateTimeProvider = dateTimeProvider;
_dataSeedService = dataSeedService;
_domainEventsQueue = domainEventsQueue;
_validator = validator;
}
@@ -79,7 +88,7 @@ public class SetupApplicationCommandHandler : ICommandHandler<SetupApplicationCo
if (validationResult.Count > 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<IEnumerable<UserEntity>> selectUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (selectUsersResult.IsFailure)
return selectUsersResult.Errors;
@@ -100,23 +109,23 @@ public class SetupApplicationCommandHandler : ICommandHandler<SetupApplicationCo
CreatedBy = id,
LibraryScans = [],
};
// if the user enabled two factor auth, include a QR with the totp secret
// If the user enabled two factor auth, include a QR with the totp secret.
if (command.Use2fa)
{
// generate a TOTP secret
// Generate a TOTP secret.
byte[] secret = _totpTokenGenerator.GenerateSecret();
// convert the secret into a QR code for the user to scan
// Convert the secret into a QR code for the user to scan.
totpSecret = _qRCodeGenerator.GenerateQrCodeDataUri(command.Username!, secret);
// store the TOTP secret in the repository, encrypted
// Store the TOTP secret in the repository, encrypted.
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(secret));
}
// insert the user
// Insert the user.
Result<Created> 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<Created> setPermissionsResult = await _dataSeedService.SetDefaultAuthorizationPermissionsAsync(id, cancellationToken).ConfigureAwait(false);
if (setPermissionsResult.IsFailure)
return setPermissionsResult.Errors;
@@ -133,8 +142,23 @@ public class SetupApplicationCommandHandler : ICommandHandler<SetupApplicationCo
if (setRoleToAdminResult.IsFailure)
return setRoleToAdminResult.Errors;
// TODO: insert the default admin profile preferences when they are implemented
// if 2FA was enabled, the TOTP secret needs to be delivered to the client unhashed, so it can be displayed
// Seed the default scheduled jobs, owned by the administrator account.
Result<Created> 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<IEnumerable<ScheduledJobEntity>> 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);
}
}
@@ -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;
/// <summary>
/// Command for adding a scheduled job.
/// </summary>
/// <param name="Name">The name of the scheduled job.</param>
/// <param name="TaskType">The type of the task executed by the scheduled job.</param>
/// <param name="ScheduleType">The type of the schedule of the scheduled job.</param>
/// <param name="IntervalMinutes">The interval in minutes of the schedule, when the schedule type is <see cref="ScheduleType.WithIntervalInMinutes"/>.</param>
/// <param name="Hour">The hour of the schedule, when the schedule type is <see cref="ScheduleType.DailyAtHourAndMinute"/>.</param>
/// <param name="Minute">The minute of the schedule, when the schedule type is <see cref="ScheduleType.DailyAtHourAndMinute"/>.</param>
[DebuggerDisplay("Name: {Name}")]
public record AddScheduledJobCommand(
string Name,
ScheduledTaskType TaskType,
ScheduleType ScheduleType,
int? IntervalMinutes,
int? Hour,
int? Minute
) : ICommand;
@@ -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;
/// <summary>
/// Handler for the command to add a scheduled job.
/// </summary>
public class AddScheduledJobCommandHandler : ICommandHandler<AddScheduledJobCommand, Result<ScheduledJobResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IValidator<AddScheduledJobCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="AddScheduledJobCommandHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public AddScheduledJobCommandHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IUnitOfWork unitOfWork,
IValidator<AddScheduledJobCommand> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
_domainEventsQueue = domainEventsQueue;
_validator = validator;
}
/// <summary>
/// Handles the command to add a scheduled job.
/// </summary>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="ScheduledJobResponse"/>, or an error message.
/// </returns>
public async Task<Result<ScheduledJobResponse>> HandleAsync(AddScheduledJobCommand command, CancellationToken cancellationToken)
{
List<Error> 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<Schedule> scheduleResult;
if (command.ScheduleType == ScheduleType.WithIntervalInMinutes)
{
Result<IntervalSchedule> intervalScheduleResult = IntervalSchedule.Create(command.IntervalMinutes ?? 0);
if (intervalScheduleResult.IsFailure)
return intervalScheduleResult.Errors;
scheduleResult = Result.From<Schedule>(intervalScheduleResult.Value);
}
else if (command.ScheduleType == ScheduleType.DailyAtHourAndMinute)
{
Result<DailySchedule> dailyScheduleResult = DailySchedule.Create(command.Hour ?? 0, command.Minute ?? 0);
if (dailyScheduleResult.IsFailure)
return dailyScheduleResult.Errors;
scheduleResult = Result.From<Schedule>(dailyScheduleResult.Value);
}
else if (command.ScheduleType == ScheduleType.OnceAtStartup)
{
Result<OnceAtStartupSchedule> onceAtStartupScheduleResult = OnceAtStartupSchedule.Create();
if (onceAtStartupScheduleResult.IsFailure)
return onceAtStartupScheduleResult.Errors;
scheduleResult = Result.From<Schedule>(onceAtStartupScheduleResult.Value);
}
else
return DomainErrors.Scheduling.InvalidScheduleType;
// Create a domain scheduled job object.
Result<ScheduledJob> 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<Created> 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();
}
}
@@ -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;
/// <summary>
/// Validates the needed validation rules for <see cref="AddScheduledJobCommand"/>.
/// </summary>
public class AddScheduledJobCommandValidator : AbstractValidator<AddScheduledJobCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="AddScheduledJobCommandValidator"/> class.
/// </summary>
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);
}
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Scheduling.Commands.FireScheduledJob;
/// <summary>
/// Command for firing the task of a scheduled job once, without affecting its execution cycle.
/// </summary>
/// <param name="ScheduledJobId">The unique identifier of the scheduled job whose task is fired.</param>
[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
public record FireScheduledJobCommand(
Guid ScheduledJobId
) : ICommand;
@@ -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;
/// <summary>
/// Handler for the command to fire the task of a scheduled job once.
/// </summary>
public class FireScheduledJobCommandHandler : ICommandHandler<FireScheduledJobCommand, Result<ScheduledJobResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IValidator<FireScheduledJobCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="FireScheduledJobCommandHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public FireScheduledJobCommandHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IUnitOfWork unitOfWork,
IValidator<FireScheduledJobCommand> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
_domainEventsQueue = domainEventsQueue;
_validator = validator;
}
/// <summary>
/// Handles the command to fire the task of a scheduled job once.
/// </summary>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a <see cref="ScheduledJobResponse"/>, or an error message.
/// </returns>
public async Task<Result<ScheduledJobResponse>> HandleAsync(FireScheduledJobCommand command, CancellationToken cancellationToken)
{
List<Error> 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<ScheduledJobEntity?> 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<ScheduledJob> scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity();
if (scheduledJobDomainResult.IsFailure)
return scheduledJobDomainResult.Errors;
Result<Success> 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();
}
}
@@ -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;
/// <summary>
/// Validates the needed validation rules for <see cref="FireScheduledJobCommand"/>.
/// </summary>
public class FireScheduledJobCommandValidator : AbstractValidator<FireScheduledJobCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="FireScheduledJobCommandValidator"/> class.
/// </summary>
public FireScheduledJobCommandValidator()
{
RuleFor(command => command.ScheduledJobId)
.NotEmpty()
.WithError(Errors.Scheduling.ScheduledJobNotFound);
}
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob;
/// <summary>
/// Command for removing a scheduled job.
/// </summary>
/// <param name="ScheduledJobId">The unique identifier of the scheduled job to remove.</param>
[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
public record RemoveScheduledJobCommand(
Guid ScheduledJobId
) : ICommand;
@@ -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;
/// <summary>
/// Handler for the command to remove a scheduled job.
/// </summary>
public class RemoveScheduledJobCommandHandler : ICommandHandler<RemoveScheduledJobCommand, Result<Success>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IScheduledJobScheduler _scheduledJobScheduler;
private readonly IValidator<RemoveScheduledJobCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="RemoveScheduledJobCommandHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
/// <param name="scheduledJobScheduler">Injected service that schedules and executes the tasks of scheduled jobs.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public RemoveScheduledJobCommandHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IScheduledJobScheduler scheduledJobScheduler,
IUnitOfWork unitOfWork,
IValidator<RemoveScheduledJobCommand> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
_domainEventsQueue = domainEventsQueue;
_scheduledJobScheduler = scheduledJobScheduler;
_validator = validator;
}
/// <summary>
/// Handles the command to remove a scheduled job.
/// </summary>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> representing either a successful operation, or an error.
/// </returns>
public async Task<Result<Success>> HandleAsync(RemoveScheduledJobCommand command, CancellationToken cancellationToken)
{
List<Error> 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<ScheduledJobEntity?> 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<ScheduledJob> 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<Success> deleteExecutionsResult = await _unitOfWork.ScheduledJobExecutionRepository.DeleteByScheduledJobIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false);
if (deleteExecutionsResult.IsFailure)
return deleteExecutionsResult.Errors;
Result<Deleted> 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;
}
}
@@ -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;
/// <summary>
/// Validates the needed validation rules for <see cref="RemoveScheduledJobCommand"/>.
/// </summary>
public class RemoveScheduledJobCommandValidator : AbstractValidator<RemoveScheduledJobCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="RemoveScheduledJobCommandValidator"/> class.
/// </summary>
public RemoveScheduledJobCommandValidator()
{
RuleFor(command => command.ScheduledJobId)
.NotEmpty()
.WithError(Errors.Scheduling.ScheduledJobNotFound);
}
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Scheduling.Commands.StartScheduledJob;
/// <summary>
/// Command for starting the execution cycle of a scheduled job.
/// </summary>
/// <param name="ScheduledJobId">The unique identifier of the scheduled job whose execution cycle is started.</param>
[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
public record StartScheduledJobCommand(
Guid ScheduledJobId
) : ICommand;
@@ -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;
/// <summary>
/// Handler for the command to start the execution cycle of a scheduled job.
/// </summary>
public class StartScheduledJobCommandHandler : ICommandHandler<StartScheduledJobCommand, Result<ScheduledJobResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IValidator<StartScheduledJobCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="StartScheduledJobCommandHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public StartScheduledJobCommandHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IUnitOfWork unitOfWork,
IValidator<StartScheduledJobCommand> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
_domainEventsQueue = domainEventsQueue;
_validator = validator;
}
/// <summary>
/// Handles the command to start the execution cycle of a scheduled job.
/// </summary>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a <see cref="ScheduledJobResponse"/>, or an error message.
/// </returns>
public async Task<Result<ScheduledJobResponse>> HandleAsync(StartScheduledJobCommand command, CancellationToken cancellationToken)
{
List<Error> 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<ScheduledJobEntity?> 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<ScheduledJob> scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity();
if (scheduledJobDomainResult.IsFailure)
return scheduledJobDomainResult.Errors;
Result<Success> startCycleResult = scheduledJobDomainResult.Value.StartCycle();
if (startCycleResult.IsFailure)
return startCycleResult.Errors;
// Persist the new status of the scheduled job.
Result<Updated> 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();
}
}
@@ -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;
/// <summary>
/// Validates the needed validation rules for <see cref="StartScheduledJobCommand"/>.
/// </summary>
public class StartScheduledJobCommandValidator : AbstractValidator<StartScheduledJobCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="StartScheduledJobCommandValidator"/> class.
/// </summary>
public StartScheduledJobCommandValidator()
{
RuleFor(command => command.ScheduledJobId)
.NotEmpty()
.WithError(Errors.Scheduling.ScheduledJobNotFound);
}
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Scheduling.Commands.StopScheduledJob;
/// <summary>
/// Command for stopping the execution cycle of a scheduled job.
/// </summary>
/// <param name="ScheduledJobId">The unique identifier of the scheduled job whose execution cycle is stopped.</param>
[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
public record StopScheduledJobCommand(
Guid ScheduledJobId
) : ICommand;
@@ -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;
/// <summary>
/// Handler for the command to stop the execution cycle of a scheduled job.
/// </summary>
public class StopScheduledJobCommandHandler : ICommandHandler<StopScheduledJobCommand, Result<ScheduledJobResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IScheduledJobScheduler _scheduledJobScheduler;
private readonly IValidator<StopScheduledJobCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="StopScheduledJobCommandHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
/// <param name="scheduledJobScheduler">Injected service that schedules and executes the tasks of scheduled jobs.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public StopScheduledJobCommandHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IScheduledJobScheduler scheduledJobScheduler,
IUnitOfWork unitOfWork,
IValidator<StopScheduledJobCommand> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
_domainEventsQueue = domainEventsQueue;
_scheduledJobScheduler = scheduledJobScheduler;
_validator = validator;
}
/// <summary>
/// Handles the command to stop the execution cycle of a scheduled job.
/// </summary>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a <see cref="ScheduledJobResponse"/>, or an error message.
/// </returns>
public async Task<Result<ScheduledJobResponse>> HandleAsync(StopScheduledJobCommand command, CancellationToken cancellationToken)
{
List<Error> 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<ScheduledJobEntity?> 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<ScheduledJob> scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity();
if (scheduledJobDomainResult.IsFailure)
return scheduledJobDomainResult.Errors;
Result<Success> stopCycleResult = scheduledJobDomainResult.Value.StopCycle();
if (stopCycleResult.IsFailure)
return stopCycleResult.Errors;
// Persist the new status of the scheduled job.
Result<Updated> 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();
}
}
@@ -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;
/// <summary>
/// Validates the needed validation rules for <see cref="StopScheduledJobCommand"/>.
/// </summary>
public class StopScheduledJobCommandValidator : AbstractValidator<StopScheduledJobCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="StopScheduledJobCommandValidator"/> class.
/// </summary>
public StopScheduledJobCommandValidator()
{
RuleFor(command => command.ScheduledJobId)
.NotEmpty()
.WithError(Errors.Scheduling.ScheduledJobNotFound);
}
}
@@ -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;
/// <summary>
/// Command for updating the display preferences of the scheduler page of the current user.
/// </summary>
/// <param name="JobTypeFilter">The type of the scheduled job tasks whose executions are shown on the scheduler page, or <see langword="null"/> when all of them are shown.</param>
/// <param name="DisplayTimeSpan">The time span, expressed in <paramref name="DisplayTimeUnit"/>, that the scheduler page shows.</param>
/// <param name="DisplayTimeUnit">The unit in which the displayed time span of the scheduler page is expressed.</param>
[DebuggerDisplay("DisplayTimeSpan: {DisplayTimeSpan} {DisplayTimeUnit}")]
public record UpdateSchedulerDisplayPreferencesCommand(
ScheduledTaskType? JobTypeFilter,
int DisplayTimeSpan,
SchedulerDisplayTimeUnit DisplayTimeUnit
) : ICommand;
@@ -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;
/// <summary>
/// Handler for the command to update the display preferences of the scheduler page of the current user.
/// </summary>
public class UpdateSchedulerDisplayPreferencesCommandHandler : ICommandHandler<UpdateSchedulerDisplayPreferencesCommand, Result<Updated>>
{
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IUnitOfWork _unitOfWork;
private readonly IValidator<UpdateSchedulerDisplayPreferencesCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateSchedulerDisplayPreferencesCommandHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public UpdateSchedulerDisplayPreferencesCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator<UpdateSchedulerDisplayPreferencesCommand> validator)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_unitOfWork = unitOfWork;
_validator = validator;
}
/// <summary>
/// Handles the command to update the display preferences of the scheduler page of the current user.
/// </summary>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> representing either a successful update, or an error.
/// </returns>
public async Task<Result<Updated>> HandleAsync(UpdateSchedulerDisplayPreferencesCommand command, CancellationToken cancellationToken)
{
List<Error> 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<Updated> upsertResult = await _unitOfWork.SchedulerDisplayPreferencesRepository.UpsertAsync(displayPreferences, cancellationToken).ConfigureAwait(false);
if (upsertResult.IsFailure)
return upsertResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return Result.Updated;
}
}
@@ -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;
/// <summary>
/// Validates the needed validation rules for <see cref="UpdateSchedulerDisplayPreferencesCommand"/>.
/// </summary>
public class UpdateSchedulerDisplayPreferencesCommandValidator : AbstractValidator<UpdateSchedulerDisplayPreferencesCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdateSchedulerDisplayPreferencesCommandValidator"/> class.
/// </summary>
public UpdateSchedulerDisplayPreferencesCommandValidator()
{
RuleFor(command => command.DisplayTimeSpan)
.GreaterThan(0)
.WithError(Errors.Scheduling.SchedulerDisplayTimeSpanMustBePositive);
}
}
@@ -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;
/// <summary>
/// Handler for the domain event raised when a scheduled job is added.
/// </summary>
public class ScheduledJobAddedDomainEventHandler : IDomainEventHandler<ScheduledJobAddedDomainEvent>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IScheduledJobNotifier _scheduledJobNotifier;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobAddedDomainEventHandler"/> class.
/// </summary>
/// <param name="scheduledJobNotifier">Injected service for notifying the scheduled job changes to SignalR clients.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public ScheduledJobAddedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_scheduledJobNotifier = scheduledJobNotifier;
}
/// <summary>
/// Handles the event raised when a scheduled job is added.
/// </summary>
/// <param name="domainEvent">The domain event to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async ValueTask HandleAsync(ScheduledJobAddedDomainEvent domainEvent, CancellationToken cancellationToken)
{
Result<IEnumerable<ScheduledJobEntity>> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getScheduledJobsResult.IsFailure)
throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
IReadOnlyList<ScheduledJobResponse> scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
}
}
@@ -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;
/// <summary>
/// Handler for the domain event raised when the execution cycle of a scheduled job is started.
/// </summary>
public class ScheduledJobCycleStartedDomainEventHandler : IDomainEventHandler<ScheduledJobCycleStartedDomainEvent>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IScheduledJobNotifier _scheduledJobNotifier;
private readonly IScheduledJobScheduler _scheduledJobScheduler;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobCycleStartedDomainEventHandler"/> class.
/// </summary>
/// <param name="scheduledJobNotifier">Injected service for notifying the scheduled job changes to SignalR clients.</param>
/// <param name="scheduledJobScheduler">Injected service that schedules and executes the tasks of scheduled jobs.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public ScheduledJobCycleStartedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IScheduledJobScheduler scheduledJobScheduler, IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_scheduledJobNotifier = scheduledJobNotifier;
_scheduledJobScheduler = scheduledJobScheduler;
}
/// <summary>
/// Handles the event raised when the execution cycle of a scheduled job is started.
/// </summary>
/// <param name="domainEvent">The domain event to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
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<IEnumerable<ScheduledJobEntity>> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getScheduledJobsResult.IsFailure)
throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
IReadOnlyList<ScheduledJobResponse> scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
}
}
@@ -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;
/// <summary>
/// Handler for the domain event raised when the execution cycle of a scheduled job is stopped.
/// </summary>
public class ScheduledJobCycleStoppedDomainEventHandler : IDomainEventHandler<ScheduledJobCycleStoppedDomainEvent>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IScheduledJobNotifier _scheduledJobNotifier;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobCycleStoppedDomainEventHandler"/> class.
/// </summary>
/// <param name="scheduledJobNotifier">Injected service for notifying the scheduled job changes to SignalR clients.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public ScheduledJobCycleStoppedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_scheduledJobNotifier = scheduledJobNotifier;
}
/// <summary>
/// Handles the event raised when the execution cycle of a scheduled job is stopped.
/// </summary>
/// <param name="domainEvent">The domain event to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async ValueTask HandleAsync(ScheduledJobCycleStoppedDomainEvent domainEvent, CancellationToken cancellationToken)
{
Result<IEnumerable<ScheduledJobEntity>> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getScheduledJobsResult.IsFailure)
throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
IReadOnlyList<ScheduledJobResponse> scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
}
}
@@ -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;
/// <summary>
/// Handler for the domain event raised when the task of a scheduled job completes its execution.
/// </summary>
public class ScheduledJobExecutionCompletedDomainEventHandler : IDomainEventHandler<ScheduledJobExecutionCompletedDomainEvent>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IScheduledJobNotifier _scheduledJobNotifier;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobExecutionCompletedDomainEventHandler"/> class.
/// </summary>
/// <param name="scheduledJobNotifier">Injected service for notifying the scheduled job changes to SignalR clients.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public ScheduledJobExecutionCompletedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_scheduledJobNotifier = scheduledJobNotifier;
}
/// <summary>
/// Handles the event raised when the task of a scheduled job completes its execution.
/// </summary>
/// <param name="domainEvent">The domain event to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async ValueTask HandleAsync(ScheduledJobExecutionCompletedDomainEvent domainEvent, CancellationToken cancellationToken)
{
// Get the scheduled job from the repository.
Result<ScheduledJobEntity?> 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<Updated> 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<ScheduledJobExecutionEntity?> 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<Updated> 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);
}
/// <summary>
/// Creates a copy of <paramref name="scheduledJob"/> with the provided status and timestamps.
/// </summary>
/// <param name="scheduledJob">The scheduled job to copy.</param>
/// <param name="status">The status of the copy.</param>
/// <param name="lastStartedOnUtc">The last start time of the copy.</param>
/// <param name="lastCompletedOnUtc">The last completion time of the copy.</param>
/// <returns>The copy of the scheduled job.</returns>
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
};
}
/// <summary>
/// Creates a copy of <paramref name="execution"/> with the provided completion time.
/// </summary>
/// <param name="execution">The execution to copy.</param>
/// <param name="completedOnUtc">The completion time of the copy.</param>
/// <returns>The copy of the execution.</returns>
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
};
}
/// <summary>
/// Notifies the SignalR clients about the current list of scheduled jobs.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task NotifyCurrentScheduledJobsAsync(CancellationToken cancellationToken)
{
Result<IEnumerable<ScheduledJobEntity>> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getScheduledJobsResult.IsFailure)
throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
IReadOnlyList<ScheduledJobResponse> scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
}
}
@@ -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;
/// <summary>
/// Handler for the domain event raised when the task of a scheduled job starts its execution.
/// </summary>
public class ScheduledJobExecutionStartedDomainEventHandler : IDomainEventHandler<ScheduledJobExecutionStartedDomainEvent>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IScheduledJobNotifier _scheduledJobNotifier;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobExecutionStartedDomainEventHandler"/> class.
/// </summary>
/// <param name="scheduledJobNotifier">Injected service for notifying the scheduled job changes to SignalR clients.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public ScheduledJobExecutionStartedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_scheduledJobNotifier = scheduledJobNotifier;
}
/// <summary>
/// Handles the event raised when the task of a scheduled job starts its execution.
/// </summary>
/// <param name="domainEvent">The domain event to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async ValueTask HandleAsync(ScheduledJobExecutionStartedDomainEvent domainEvent, CancellationToken cancellationToken)
{
// Get the scheduled job from the repository.
Result<ScheduledJobEntity?> 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<Updated> 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<Created> 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);
}
/// <summary>
/// Creates a copy of <paramref name="scheduledJob"/> with the provided status and timestamps.
/// </summary>
/// <param name="scheduledJob">The scheduled job to copy.</param>
/// <param name="status">The status of the copy.</param>
/// <param name="lastStartedOnUtc">The last start time of the copy.</param>
/// <param name="lastCompletedOnUtc">The last completion time of the copy.</param>
/// <returns>The copy of the scheduled job.</returns>
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
};
}
/// <summary>
/// Notifies the SignalR clients about the current list of scheduled jobs.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task NotifyCurrentScheduledJobsAsync(CancellationToken cancellationToken)
{
Result<IEnumerable<ScheduledJobEntity>> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getScheduledJobsResult.IsFailure)
throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
IReadOnlyList<ScheduledJobResponse> scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
}
}
@@ -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;
/// <summary>
/// Handler for the domain event raised when the execution of the task of a scheduled job is stopped while it is running.
/// </summary>
public class ScheduledJobExecutionStoppedDomainEventHandler : IDomainEventHandler<ScheduledJobExecutionStoppedDomainEvent>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IScheduledJobNotifier _scheduledJobNotifier;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobExecutionStoppedDomainEventHandler"/> class.
/// </summary>
/// <param name="scheduledJobNotifier">Injected service for notifying the scheduled job changes to SignalR clients.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public ScheduledJobExecutionStoppedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_scheduledJobNotifier = scheduledJobNotifier;
}
/// <summary>
/// Handles the event raised when the execution of the task of a scheduled job is stopped while it is running.
/// </summary>
/// <param name="domainEvent">The domain event to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async ValueTask HandleAsync(ScheduledJobExecutionStoppedDomainEvent domainEvent, CancellationToken cancellationToken)
{
// Close the execution history row of the stopped execution, if it exists.
Result<ScheduledJobExecutionEntity?> 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<Updated> 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<IEnumerable<ScheduledJobEntity>> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getScheduledJobsResult.IsFailure)
throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
IReadOnlyList<ScheduledJobResponse> scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
}
}
@@ -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;
/// <summary>
/// Handler for the domain event raised when the task of a scheduled job is fired once.
/// </summary>
public class ScheduledJobFiredDomainEventHandler : IDomainEventHandler<ScheduledJobFiredDomainEvent>
{
private readonly IScheduledJobScheduler _scheduledJobScheduler;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobFiredDomainEventHandler"/> class.
/// </summary>
/// <param name="scheduledJobScheduler">Injected service that schedules and executes the tasks of scheduled jobs.</param>
public ScheduledJobFiredDomainEventHandler(IScheduledJobScheduler scheduledJobScheduler)
{
_scheduledJobScheduler = scheduledJobScheduler;
}
/// <summary>
/// Handles the event raised when the task of a scheduled job is fired once.
/// </summary>
/// <param name="domainEvent">The domain event to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
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);
}
}
@@ -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;
/// <summary>
/// Handler for the domain event raised when a scheduled job is removed.
/// </summary>
public class ScheduledJobRemovedDomainEventHandler : IDomainEventHandler<ScheduledJobRemovedDomainEvent>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IScheduledJobNotifier _scheduledJobNotifier;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobRemovedDomainEventHandler"/> class.
/// </summary>
/// <param name="scheduledJobNotifier">Injected service for notifying the scheduled job changes to SignalR clients.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public ScheduledJobRemovedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_scheduledJobNotifier = scheduledJobNotifier;
}
/// <summary>
/// Handles the event raised when a scheduled job is removed.
/// </summary>
/// <param name="domainEvent">The domain event to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async ValueTask HandleAsync(ScheduledJobRemovedDomainEvent domainEvent, CancellationToken cancellationToken)
{
Result<IEnumerable<ScheduledJobEntity>> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getScheduledJobsResult.IsFailure)
throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
IReadOnlyList<ScheduledJobResponse> scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
}
}
@@ -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;
/// <summary>
/// Interface for the class used to notify SignalR clients about the scheduled jobs and their executions.
/// </summary>
public interface IScheduledJobNotifier
{
/// <summary>
/// Notifies the SignalR clients about the current list of scheduled jobs.
/// </summary>
/// <param name="scheduledJobs">The current list of scheduled jobs.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
Task SendScheduledJobsAsync(IReadOnlyList<ScheduledJobResponse> scheduledJobs, CancellationToken cancellationToken);
/// <summary>
/// Notifies the SignalR clients about an execution of the task of a scheduled job that started.
/// </summary>
/// <param name="execution">The execution of the task of the scheduled job that started.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
Task SendScheduledJobExecutionStartedAsync(ScheduledJobExecutionResponse execution, CancellationToken cancellationToken);
/// <summary>
/// Notifies the SignalR clients about an execution of the task of a scheduled job that completed.
/// </summary>
/// <param name="execution">The execution of the task of the scheduled job that completed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
Task SendScheduledJobExecutionCompletedAsync(ScheduledJobExecutionResponse execution, CancellationToken cancellationToken);
}
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Scheduling.Queries.GetScheduledJobHistory;
/// <summary>
/// Query for getting the history of the executions of the tasks of scheduled jobs.
/// </summary>
/// <param name="From">The optional inclusive lower bound of the interval for which the history is requested.</param>
/// <param name="To">The optional inclusive upper bound of the interval for which the history is requested.</param>
[DebuggerDisplay("From: {From}, To: {To}")]
public record GetScheduledJobHistoryQuery(
DateTime? From,
DateTime? To
) : IQuery;
@@ -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;
/// <summary>
/// Handler for the query to get the history of the executions of the tasks of scheduled jobs.
/// </summary>
public class GetScheduledJobHistoryQueryHandler : IQueryHandler<GetScheduledJobHistoryQuery, Result<IEnumerable<ScheduledJobExecutionResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
/// <summary>
/// Initializes a new instance of the <see cref="GetScheduledJobHistoryQueryHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public GetScheduledJobHistoryQueryHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
}
/// <summary>
/// Handles the query to get the history of the executions of the tasks of scheduled jobs.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the execution history, or an error.
/// </returns>
public async Task<Result<IEnumerable<ScheduledJobExecutionResponse>>> 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<IEnumerable<ScheduledJobExecutionEntity>> 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()));
}
}
@@ -0,0 +1,12 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Scheduling.Queries.GetScheduledJobs;
/// <summary>
/// Query for getting the list of scheduled jobs.
/// </summary>
[DebuggerDisplay("GetScheduledJobsQuery")]
public record GetScheduledJobsQuery : IQuery;
@@ -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;
/// <summary>
/// Handler for the query to get the list of scheduled jobs.
/// </summary>
public class GetScheduledJobsQueryHandler : IQueryHandler<GetScheduledJobsQuery, Result<IEnumerable<ScheduledJobResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
/// <summary>
/// Initializes a new instance of the <see cref="GetScheduledJobsQueryHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public GetScheduledJobsQueryHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
}
/// <summary>
/// Handles the query to get the list of scheduled jobs.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the list of scheduled jobs, or an error.
/// </returns>
public async Task<Result<IEnumerable<ScheduledJobResponse>>> 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<IEnumerable<ScheduledJobEntity>> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getScheduledJobsResult.IsFailure)
return getScheduledJobsResult.Errors;
return Result.From(getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse()));
}
}
@@ -0,0 +1,10 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
#endregion
namespace Lumina.Application.Core.Scheduling.Queries.GetSchedulerDisplayPreferences;
/// <summary>
/// Query for getting the display preferences of the scheduler page of the current user.
/// </summary>
public record GetSchedulerDisplayPreferencesQuery : IQuery;
@@ -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;
/// <summary>
/// Handler for the query to get the display preferences of the scheduler page of the current user.
/// </summary>
public class GetSchedulerDisplayPreferencesQueryHandler : IQueryHandler<GetSchedulerDisplayPreferencesQuery, Result<SchedulerDisplayPreferencesResponse>>
{
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IUnitOfWork _unitOfWork;
/// <summary>
/// Initializes a new instance of the <see cref="GetSchedulerDisplayPreferencesQueryHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public GetSchedulerDisplayPreferencesQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_unitOfWork = unitOfWork;
}
/// <summary>
/// Handles the query to get the display preferences of the scheduler page of the current user.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the display preferences of the scheduler page of the current user, or an error.
/// </returns>
public async Task<Result<SchedulerDisplayPreferencesResponse>> 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<SchedulerDisplayPreferencesEntity?> 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();
}
}
@@ -0,0 +1,26 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.Scheduling;
/// <summary>
/// Represents a request to add a scheduled job.
/// </summary>
/// <param name="Name">The name of the scheduled job. Required.</param>
/// <param name="TaskType">The type of the task executed by the scheduled job. Required.</param>
/// <param name="ScheduleType">The type of the schedule of the scheduled job. Required.</param>
/// <param name="IntervalMinutes">The interval in minutes of the schedule, required when <paramref name="ScheduleType"/> is <see cref="ScheduleType.WithIntervalInMinutes"/>.</param>
/// <param name="Hour">The hour of the schedule, required when <paramref name="ScheduleType"/> is <see cref="ScheduleType.DailyAtHourAndMinute"/>.</param>
/// <param name="Minute">The minute of the schedule, required when <paramref name="ScheduleType"/> is <see cref="ScheduleType.DailyAtHourAndMinute"/>.</param>
[DebuggerDisplay("Name: {Name}")]
public record AddScheduledJobRequest(
string Name,
ScheduledTaskType TaskType,
ScheduleType ScheduleType,
int? IntervalMinutes,
int? Hour,
int? Minute
);
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.Scheduling;
/// <summary>
/// Represents a request to fire the task of a scheduled job once, without affecting its execution cycle.
/// </summary>
/// <param name="ScheduledJobId">The unique identifier of the scheduled job whose task is fired. Required.</param>
[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
public record FireScheduledJobRequest(
Guid ScheduledJobId
);
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.Scheduling;
/// <summary>
/// Represents a request to get the history of the executions of the tasks of scheduled jobs.
/// </summary>
/// <param name="From">The inclusive lower bound of the interval for which the history is requested. Optional.</param>
/// <param name="To">The inclusive upper bound of the interval for which the history is requested. Optional.</param>
[DebuggerDisplay("From: {From}, To: {To}")]
public record GetScheduledJobHistoryRequest(
DateTime? From,
DateTime? To
);
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.Scheduling;
/// <summary>
/// Represents a request to remove a scheduled job.
/// </summary>
/// <param name="ScheduledJobId">The unique identifier of the scheduled job to remove. Required.</param>
[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
public record RemoveScheduledJobRequest(
Guid ScheduledJobId
);
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.Scheduling;
/// <summary>
/// Represents a request to start the execution cycle of a scheduled job.
/// </summary>
/// <param name="ScheduledJobId">The unique identifier of the scheduled job whose execution cycle is started. Required.</param>
[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
public record StartScheduledJobRequest(
Guid ScheduledJobId
);
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.Scheduling;
/// <summary>
/// Represents a request to stop the execution cycle of a scheduled job.
/// </summary>
/// <param name="ScheduledJobId">The unique identifier of the scheduled job whose execution cycle is stopped. Required.</param>
[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
public record StopScheduledJobRequest(
Guid ScheduledJobId
);
@@ -0,0 +1,19 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.Scheduling;
/// <summary>
/// Represents a request to update the display preferences of the scheduler page of the current user.
/// </summary>
/// <param name="JobTypeFilter">The type of the scheduled job tasks whose executions are shown on the scheduler page, or <see langword="null"/> when all of them are shown.</param>
/// <param name="DisplayTimeSpan">The time span, expressed in <paramref name="DisplayTimeUnit"/>, that the scheduler page shows. Required.</param>
/// <param name="DisplayTimeUnit">The unit in which the displayed time span of the scheduler page is expressed. Required.</param>
[DebuggerDisplay("DisplayTimeSpan: {DisplayTimeSpan} {DisplayTimeUnit}")]
public sealed record UpdateSchedulerDisplayPreferencesRequest(
ScheduledTaskType? JobTypeFilter,
int DisplayTimeSpan,
SchedulerDisplayTimeUnit DisplayTimeUnit
);
@@ -0,0 +1,26 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.Scheduling;
/// <summary>
/// Represents an execution of the task of a scheduled job.
/// </summary>
/// <param name="Id">The unique identifier of the execution.</param>
/// <param name="ScheduledJobId">The unique identifier of the scheduled job whose task was executed.</param>
/// <param name="TaskType">The type of the task that was executed.</param>
/// <param name="IsCycleRun"><see langword="true"/> when the execution was triggered by the execution cycle of the scheduled job, <see langword="false"/> when it was a one time execution.</param>
/// <param name="StartedOnUtc">The date and time when the execution started.</param>
/// <param name="CompletedOnUtc">The optional date and time when the execution completed.</param>
[DebuggerDisplay("Id: {Id}, ScheduledJobId: {ScheduledJobId}")]
public record ScheduledJobExecutionResponse(
Guid Id,
Guid ScheduledJobId,
ScheduledTaskType TaskType,
bool IsCycleRun,
DateTime StartedOnUtc,
DateTime? CompletedOnUtc
);
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.Scheduling;
/// <summary>
/// Represents a scheduled job response.
/// </summary>
/// <param name="Id">The unique identifier of the scheduled job.</param>
/// <param name="Name">The name of the scheduled job.</param>
/// <param name="TaskType">The type of the task executed by the scheduled job.</param>
/// <param name="ScheduleType">The type of the schedule of the scheduled job.</param>
/// <param name="IntervalMinutes">The interval in minutes of the schedule of the scheduled job, when its <see cref="ScheduleType"/> is <see cref="ScheduleType.WithIntervalInMinutes"/>.</param>
/// <param name="Hour">The hour of the schedule of the scheduled job, when its <see cref="ScheduleType"/> is <see cref="ScheduleType.DailyAtHourAndMinute"/>.</param>
/// <param name="Minute">The minute of the schedule of the scheduled job, when its <see cref="ScheduleType"/> is <see cref="ScheduleType.DailyAtHourAndMinute"/>.</param>
/// <param name="Status">The status of the scheduled job.</param>
/// <param name="LastStartedOnUtc">The optional date and time when the task of the scheduled job last started its execution.</param>
/// <param name="LastCompletedOnUtc">The optional date and time when the task of the scheduled job last completed its execution.</param>
[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
);
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.Scheduling;
/// <summary>
/// Represents the display preferences of the scheduler page of a user.
/// </summary>
/// <param name="UserId">The unique identifier of the user that owns the display preferences.</param>
/// <param name="JobTypeFilter">The type of the scheduled job tasks whose executions are shown on the scheduler page, or <see langword="null"/> when all of them are shown.</param>
/// <param name="DisplayTimeSpan">The time span, expressed in <paramref name="DisplayTimeUnit"/>, that the scheduler page shows.</param>
/// <param name="DisplayTimeUnit">The unit in which the displayed time span of the scheduler page is expressed.</param>
[DebuggerDisplay("UserId: {UserId}, DisplayTimeSpan: {DisplayTimeSpan} {DisplayTimeUnit}")]
public sealed record SchedulerDisplayPreferencesResponse(
Guid UserId,
ScheduledTaskType? JobTypeFilter,
int DisplayTimeSpan,
SchedulerDisplayTimeUnit DisplayTimeUnit
);
@@ -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;
/// <summary>
/// Configures the entity mapping for the <see cref="ScheduledJobEntity"/> entity.
/// </summary>
public class ScheduledJobConfiguration : IEntityTypeConfiguration<ScheduledJobEntity>
{
/// <summary>
/// Configures the <see cref="ScheduledJobEntity"/> entity.
/// </summary>
/// <param name="builder">The builder to be used to configure the entity.</param>
public void Configure(EntityTypeBuilder<ScheduledJobEntity> 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<string>()
.HasColumnOrder(2);
builder.Property(scheduledJob => scheduledJob.ScheduleType)
.IsRequired()
.HasConversion<string>()
.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<string>()
.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);
}
}
@@ -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;
/// <summary>
/// Configures the entity mapping for the <see cref="ScheduledJobExecutionEntity"/> entity.
/// </summary>
public class ScheduledJobExecutionConfiguration : IEntityTypeConfiguration<ScheduledJobExecutionEntity>
{
/// <summary>
/// Configures the <see cref="ScheduledJobExecutionEntity"/> entity.
/// </summary>
/// <param name="builder">The builder to be used to configure the entity.</param>
public void Configure(EntityTypeBuilder<ScheduledJobExecutionEntity> 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<string>()
.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);
}
}
@@ -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;
/// <summary>
/// Configures the entity mapping for the <see cref="SchedulerDisplayPreferencesEntity"/> entity.
/// </summary>
public class SchedulerDisplayPreferencesConfiguration : IEntityTypeConfiguration<SchedulerDisplayPreferencesEntity>
{
/// <summary>
/// Configures the <see cref="SchedulerDisplayPreferencesEntity"/> entity.
/// </summary>
/// <param name="builder">The builder to be used to configure the entity.</param>
public void Configure(EntityTypeBuilder<SchedulerDisplayPreferencesEntity> 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<string>()
.HasColumnOrder(2);
builder.Property(preferences => preferences.DisplayTimeSpan)
.IsRequired()
.HasColumnOrder(3);
builder.Property(preferences => preferences.DisplayTimeUnit)
.IsRequired()
.HasConversion<string>()
.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();
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,85 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Lumina.DataAccess.Common.Migrations
{
/// <inheritdoc />
public partial class AddsScheduledJobsTables : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "ScheduledJobExecutions",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
ScheduledJobId = table.Column<Guid>(type: "TEXT", nullable: false),
TaskType = table.Column<string>(type: "TEXT", nullable: false),
IsCycleRun = table.Column<bool>(type: "INTEGER", nullable: false),
StartedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
CompletedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
UpdatedBy = table.Column<Guid>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ScheduledJobExecutions", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ScheduledJobs",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
Name = table.Column<string>(type: "TEXT", nullable: false),
TaskType = table.Column<string>(type: "TEXT", nullable: false),
ScheduleType = table.Column<string>(type: "TEXT", nullable: false),
IntervalMinutes = table.Column<int>(type: "INTEGER", nullable: true),
Hour = table.Column<int>(type: "INTEGER", nullable: true),
Minute = table.Column<int>(type: "INTEGER", nullable: true),
Status = table.Column<string>(type: "TEXT", nullable: false),
OwnerUserId = table.Column<Guid>(type: "TEXT", nullable: false),
LastStartedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
LastCompletedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
UpdatedBy = table.Column<Guid>(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");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ScheduledJobExecutions");
migrationBuilder.DropTable(
name: "ScheduledJobs");
}
}
}
@@ -0,0 +1,47 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Lumina.DataAccess.Common.Migrations
{
/// <inheritdoc />
public partial class AddsSchedulerDisplayPreferences : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "SchedulerDisplayPreferences",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
UserId = table.Column<Guid>(type: "TEXT", nullable: false),
JobTypeFilter = table.Column<string>(type: "TEXT", nullable: true),
DisplayTimeSpan = table.Column<int>(type: "INTEGER", nullable: false),
DisplayTimeUnit = table.Column<string>(type: "TEXT", nullable: false),
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
UpdatedBy = table.Column<Guid>(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);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "SchedulerDisplayPreferences");
}
}
}
@@ -0,0 +1,115 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Lumina.DataAccess.Common.Migrations
{
/// <inheritdoc />
public partial class AddsWasCycleActiveToScheduledJobExecutions : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<DateTime>(
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<Guid>(
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<DateTime>(
name: "CreatedOnUtc",
table: "ScheduledJobExecutions",
type: "TEXT",
nullable: false,
oldClrType: typeof(DateTime),
oldType: "TEXT")
.Annotation("Relational:ColumnOrder", 7)
.OldAnnotation("Relational:ColumnOrder", 6);
migrationBuilder.AlterColumn<Guid>(
name: "CreatedBy",
table: "ScheduledJobExecutions",
type: "TEXT",
nullable: false,
oldClrType: typeof(Guid),
oldType: "TEXT")
.Annotation("Relational:ColumnOrder", 8)
.OldAnnotation("Relational:ColumnOrder", 7);
migrationBuilder.AddColumn<bool>(
name: "WasCycleActive",
table: "ScheduledJobExecutions",
type: "INTEGER",
nullable: false,
defaultValue: false)
.Annotation("Relational:ColumnOrder", 6);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "WasCycleActive",
table: "ScheduledJobExecutions");
migrationBuilder.AlterColumn<DateTime>(
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<Guid>(
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<DateTime>(
name: "CreatedOnUtc",
table: "ScheduledJobExecutions",
type: "TEXT",
nullable: false,
oldClrType: typeof(DateTime),
oldType: "TEXT")
.Annotation("Relational:ColumnOrder", 6)
.OldAnnotation("Relational:ColumnOrder", 7);
migrationBuilder.AlterColumn<Guid>(
name: "CreatedBy",
table: "ScheduledJobExecutions",
type: "TEXT",
nullable: false,
oldClrType: typeof(Guid),
oldType: "TEXT")
.Annotation("Relational:ColumnOrder", 7)
.OldAnnotation("Relational:ColumnOrder", 8);
}
}
}
@@ -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<Guid>("Id")
.HasColumnType("TEXT")
.HasColumnOrder(0);
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(12);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(11);
b.Property<int?>("Hour")
.HasColumnType("INTEGER")
.HasColumnOrder(5);
b.Property<int?>("IntervalMinutes")
.HasColumnType("INTEGER")
.HasColumnOrder(4);
b.Property<DateTime?>("LastCompletedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(10);
b.Property<DateTime?>("LastStartedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(9);
b.Property<int?>("Minute")
.HasColumnType("INTEGER")
.HasColumnOrder(6);
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<Guid>("OwnerUserId")
.HasColumnType("TEXT")
.HasColumnOrder(8);
b.Property<string>("ScheduleType")
.IsRequired()
.HasColumnType("TEXT")
.HasColumnOrder(3);
b.Property<string>("Status")
.IsRequired()
.HasColumnType("TEXT")
.HasColumnOrder(7);
b.Property<string>("TaskType")
.IsRequired()
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(14);
b.Property<DateTime?>("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<Guid>("Id")
.HasColumnType("TEXT")
.HasColumnOrder(0);
b.Property<DateTime?>("CompletedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(5);
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(8);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(7);
b.Property<bool>("IsCycleRun")
.HasColumnType("INTEGER")
.HasColumnOrder(3);
b.Property<Guid>("ScheduledJobId")
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<DateTime>("StartedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(4);
b.Property<string>("TaskType")
.IsRequired()
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(10);
b.Property<DateTime?>("UpdatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(9);
b.Property<bool>("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<Guid>("Id")
.HasColumnType("TEXT")
.HasColumnOrder(0);
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(6);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(5);
b.Property<int>("DisplayTimeSpan")
.HasColumnType("INTEGER")
.HasColumnOrder(3);
b.Property<string>("DisplayTimeUnit")
.IsRequired()
.HasColumnType("TEXT")
.HasColumnOrder(4);
b.Property<string>("JobTypeFilter")
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(8);
b.Property<DateTime?>("UpdatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(7);
b.Property<Guid>("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<Guid>("Id")
@@ -1257,14 +1433,14 @@ namespace Lumina.DataAccess.Common.Migrations
.HasColumnType("INTEGER")
.HasColumnOrder(4);
b.Property<bool>("ShouldRenderPdfAsImages")
.HasColumnType("INTEGER")
.HasColumnOrder(11);
b.Property<bool>("ShouldPreserveBookStyles")
.HasColumnType("INTEGER")
.HasColumnOrder(12);
b.Property<bool>("ShouldRenderPdfAsImages")
.HasColumnType("INTEGER")
.HasColumnOrder(11);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(8);
@@ -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;
/// <summary>
/// Repository for the executions of the tasks of scheduled jobs.
/// </summary>
internal sealed class ScheduledJobExecutionRepository : IScheduledJobExecutionRepository
{
private readonly LuminaDbContext _luminaDbContext;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobExecutionRepository"/> class.
/// </summary>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
public ScheduledJobExecutionRepository(LuminaDbContext luminaDbContext)
{
_luminaDbContext = luminaDbContext;
}
/// <summary>
/// Gets an execution identified by <paramref name="id"/> from the storage medium.
/// </summary>
/// <param name="id">The id of the execution to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="ScheduledJobExecutionEntity"/> identified by <paramref name="id"/>, or an error.</returns>
public async Task<Result<ScheduledJobExecutionEntity?>> 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);
}
/// <summary>
/// Adds a new execution of the task of a scheduled job.
/// </summary>
/// <param name="execution">The execution to add.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> 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;
}
/// <summary>
/// Updates an execution of the task of a scheduled job.
/// </summary>
/// <param name="data">The execution to update.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Updated>> 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;
}
/// <summary>
/// Gets the most recent execution of the task of a scheduled job identified by <paramref name="scheduledJobId"/> that is still running, from the storage medium.
/// </summary>
/// <param name="scheduledJobId">The Id of the scheduled job whose running execution is retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the running execution of the scheduled job, or <see langword="null"/>.</returns>
public async Task<Result<ScheduledJobExecutionEntity?>> 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);
}
/// <summary>
/// Gets the executions of the tasks of scheduled jobs that started in the interval between <paramref name="fromUtc"/> and <paramref name="toUtc"/>, from the storage medium.
/// </summary>
/// <param name="fromUtc">The inclusive lower bound of the interval, in UTC.</param>
/// <param name="toUtc">The inclusive upper bound of the interval, in UTC.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="ScheduledJobExecutionEntity"/>, or an error.</returns>
public async Task<Result<IEnumerable<ScheduledJobExecutionEntity>>> 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);
}
/// <summary>
/// Removes all the executions of the task of a scheduled job identified by <paramref name="scheduledJobId"/>, from the storage medium.
/// </summary>
/// <param name="scheduledJobId">The Id of the scheduled job whose executions are removed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Success>> 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;
}
/// <summary>
/// Removes all the executions of the tasks of scheduled jobs that started before <paramref name="cutoffUtc"/>, from the storage medium.
/// </summary>
/// <param name="cutoffUtc">The exclusive lower bound of the retained interval, in UTC; executions that started before it are removed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Success>> 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;
}
}
@@ -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;
/// <summary>
/// Repository for scheduled jobs.
/// </summary>
internal sealed class ScheduledJobRepository : IScheduledJobRepository
{
private readonly LuminaDbContext _luminaDbContext;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobRepository"/> class.
/// </summary>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
public ScheduledJobRepository(LuminaDbContext luminaDbContext)
{
_luminaDbContext = luminaDbContext;
}
/// <summary>
/// Gets a scheduled job identified by <paramref name="id"/> from the storage medium.
/// </summary>
/// <param name="id">The id of the scheduled job to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="ScheduledJobEntity"/> identified by <paramref name="id"/>, or an error.</returns>
public async Task<Result<ScheduledJobEntity?>> 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);
}
/// <summary>
/// Gets a scheduled job identified by <paramref name="id"/> from the storage medium, without tracking it.
/// </summary>
/// <param name="id">The id of the scheduled job to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="ScheduledJobEntity"/> identified by <paramref name="id"/>, or an error.</returns>
public async Task<Result<ScheduledJobEntity?>> 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);
}
/// <summary>
/// Gets all scheduled jobs from the storage medium.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="ScheduledJobEntity"/>, or an error.</returns>
public async Task<Result<IEnumerable<ScheduledJobEntity>>> GetAllAsync(CancellationToken cancellationToken)
{
return await _luminaDbContext.ScheduledJobs
.ToListAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the scheduled jobs that have an active or running execution cycle, from the storage medium.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="ScheduledJobEntity"/>, or an error.</returns>
public async Task<Result<IEnumerable<ScheduledJobEntity>>> GetActiveOrRunningAsync(CancellationToken cancellationToken)
{
return await _luminaDbContext.ScheduledJobs
.Where(scheduledJob => scheduledJob.Status == ScheduledJobStatus.Active || scheduledJob.Status == ScheduledJobStatus.Running)
.ToListAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Adds a new scheduled job.
/// </summary>
/// <param name="scheduledJob">The scheduled job to add.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> 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;
}
/// <summary>
/// Updates a scheduled job.
/// </summary>
/// <param name="data">The scheduled job to update.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Updated>> 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;
}
/// <summary>
/// Removes a scheduled job identified by <paramref name="id"/> from the storage medium.
/// </summary>
/// <param name="id">The id of the scheduled job to remove.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> 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;
}
}
@@ -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;
/// <summary>
/// Repository for the display preferences of the scheduler page.
/// </summary>
internal sealed class SchedulerDisplayPreferencesRepository : ISchedulerDisplayPreferencesRepository
{
private readonly LuminaDbContext _luminaDbContext;
/// <summary>
/// Initializes a new instance of the <see cref="SchedulerDisplayPreferencesRepository"/> class.
/// </summary>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
public SchedulerDisplayPreferencesRepository(LuminaDbContext luminaDbContext)
{
_luminaDbContext = luminaDbContext;
}
/// <summary>
/// Gets the display preferences of the scheduler page of the user identified by <paramref name="userId"/>, if they exist.
/// </summary>
/// <param name="userId">The Id of the user whose display preferences are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the display preferences of the user, or an error.</returns>
public async Task<Result<SchedulerDisplayPreferencesEntity?>> GetByUserIdAsync(Guid userId, CancellationToken cancellationToken)
{
return await _luminaDbContext.SchedulerDisplayPreferences
.FirstOrDefaultAsync(preferences => preferences.UserId == userId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Inserts the display preferences of the scheduler page of a user, or updates them when they already exist.
/// </summary>
/// <param name="preferences">The display preferences to insert or update.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Updated>> 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;
}
}
@@ -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
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> 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
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> 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
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> SetAdminRolePermissionsAsync(Guid userId, CancellationToken cancellationToken)
{
// get the admin role
// Get the admin role.
Result<RoleEntity?> 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<IEnumerable<PermissionEntity>> 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
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> SetAdminRoleToAdministratorAccount(Guid userId, CancellationToken cancellationToken)
{
// get the admin role
// Get the admin role.
Result<RoleEntity?> 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<UserEntity?> 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;
}
/// <summary>
/// Sets up the default scheduled jobs, owned by the administrator account.
/// </summary>
/// <param name="adminUserId">The unique identifier of the administrator account that owns the default scheduled jobs.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> 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<Created> insertScheduledJobResult = await _unitOfWork.ScheduledJobRepository.InsertAsync(defaultScheduledJob, cancellationToken).ConfigureAwait(false);
if (insertScheduledJobResult.IsFailure)
return insertScheduledJobResult.Errors;
}
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return Result.Created;
}
/// <summary>
/// Creates a default scheduled job with its execution cycle active, owned by the administrator account identified by <paramref name="adminUserId"/>.
/// </summary>
/// <param name="name">The name of the default scheduled job.</param>
/// <param name="taskType">The type of the task executed by the default scheduled job.</param>
/// <param name="scheduleType">The type of the schedule of the default scheduled job.</param>
/// <param name="intervalMinutes">The interval in minutes of the schedule, when it is an interval schedule.</param>
/// <param name="hour">The hour of the schedule, when it is a daily schedule.</param>
/// <param name="minute">The minute of the schedule, when it is a daily schedule.</param>
/// <param name="adminUserId">The unique identifier of the administrator account that owns the default scheduled job.</param>
/// <returns>The created default scheduled job.</returns>
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
};
}
}
@@ -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<ThemeEntity> Themes { get; set; } = null!;
public virtual DbSet<MediaContributorEntity> MediaContributors { get; set; } = null!;
public virtual DbSet<BookContributorEntity> BookContributors { get; set; } = null!;
public virtual DbSet<ScheduledJobEntity> ScheduledJobs { get; set; } = null!;
public virtual DbSet<ScheduledJobExecutionEntity> ScheduledJobExecutions { get; set; } = null!;
public virtual DbSet<SchedulerDisplayPreferencesEntity> SchedulerDisplayPreferences { get; set; } = null!;
/// <summary>
/// Initializes a new instance of the <see cref="LuminaDbContext"/> class.
@@ -54,7 +58,7 @@ public class LuminaDbContext : DbContext
/// <param name="modelBuilder">The model builder used to configure the entity mappings.</param>
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);
@@ -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
}
}
/// <summary>
/// Gets the scheduled job repository.
/// </summary>
public IScheduledJobRepository ScheduledJobRepository
{
get
{
_scheduledJobRepository ??= new ScheduledJobRepository(_luminaDbContext);
return _scheduledJobRepository;
}
}
/// <summary>
/// Gets the scheduled job execution repository.
/// </summary>
public IScheduledJobExecutionRepository ScheduledJobExecutionRepository
{
get
{
_scheduledJobExecutionRepository ??= new ScheduledJobExecutionRepository(_luminaDbContext);
return _scheduledJobExecutionRepository;
}
}
/// <summary>
/// Gets the scheduler display preferences repository.
/// </summary>
public ISchedulerDisplayPreferencesRepository SchedulerDisplayPreferencesRepository
{
get
{
_schedulerDisplayPreferencesRepository ??= new SchedulerDisplayPreferencesRepository(_luminaDbContext);
return _schedulerDisplayPreferencesRepository;
}
}
/// <summary>
/// Gets the plugin repository.
/// </summary>
@@ -0,0 +1,22 @@
namespace Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
/// <summary>
/// Enumeration for the types of schedules of scheduled jobs.
/// </summary>
public enum ScheduleType
{
/// <summary>
/// The scheduled job repeats with an interval measured in minutes.
/// </summary>
WithIntervalInMinutes,
/// <summary>
/// The scheduled job repeats daily at a fixed hour and minute.
/// </summary>
DailyAtHourAndMinute,
/// <summary>
/// The scheduled job fires its task once, every time the application starts.
/// </summary>
OnceAtStartup
}
Loaded 100 of 421 files, more files were not shown because too many files have changed in this diff. Show more