diff --git a/.github/dependabot.yml b/.github/dependabot.yml
index 3258ab7..01a9d2a 100644
--- a/.github/dependabot.yml
+++ b/.github/dependabot.yml
@@ -11,6 +11,11 @@ updates:
patterns: ["*"]
multi-ecosystem-group: "monthly-dependencies"
+ - package-ecosystem: "docker-compose"
+ directory: "/"
+ patterns: ["*"]
+ multi-ecosystem-group: "monthly-dependencies"
+
- package-ecosystem: "github-actions"
directory: "/"
patterns: ["*"]
diff --git a/.github/release.yml b/.github/release.yml
index 58d0ba6..92dcb94 100644
--- a/.github/release.yml
+++ b/.github/release.yml
@@ -1,11 +1,26 @@
changelog:
+ exclude:
+ labels:
+ - ignore-for-release
categories:
- - title: Changes
+ - title: Breaking changes
labels:
- - "*"
- exclude:
- labels:
- - dependencies
+ - breaking-change
+ - title: New features
+ labels:
+ - enhancement
+ - title: Bug fixes
+ labels:
+ - bug
+ - title: Documentation
+ labels:
+ - documentation
+ - title: Build and pipeline
+ labels:
+ - build
- title: Dependencies
labels:
- dependencies
+ - title: Other changes
+ labels:
+ - "*"
diff --git a/.github/workflows/build-pipeline.yml b/.github/workflows/build-pipeline.yml
index a7a6f50..97e9b4d 100644
--- a/.github/workflows/build-pipeline.yml
+++ b/.github/workflows/build-pipeline.yml
@@ -92,6 +92,10 @@ jobs:
with:
dotnet-version: '10.0.x'
+ - name: Format
+ id: format
+ run: dotnet format --verify-no-changes --verbosity diagnostic
+
- name: Pack
id: pack
run: |
@@ -290,7 +294,7 @@ jobs:
name: Publish
runs-on: ubuntu-latest
needs: [build, coverage, scan, analysis]
- if: ${{ github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') }}
+ if: ${{ github.repository == 'stphnwlsh/CleanModelContextProtocol' && github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') }}
permissions:
contents: write
id-token: write
diff --git a/.gitignore b/.gitignore
index 702fd02..9f74819 100644
--- a/.gitignore
+++ b/.gitignore
@@ -366,3 +366,9 @@ out/
.Trashes
ehthumbs.db
Thumbs.db
+
+# SQLite databases and coverage reports
+*.db
+*.db-shm
+*.db-wal
+coverage.cobertura.xml
diff --git a/Directory.Build.props b/Directory.Build.props
index 8db3048..c56dd90 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -5,8 +5,19 @@
CleanModelContextProtocol.$(AssemblyName)
AnyCPU
enable
+ enable
true
latest
+
+
+ latest-recommended
+ true
+ true
+
+ true
+ $(NoWarn);1591
+
+
diff --git a/Directory.Packages.props b/Directory.Packages.props
new file mode 100644
index 0000000..8f24354
--- /dev/null
+++ b/Directory.Packages.props
@@ -0,0 +1,33 @@
+
+
+
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Dockerfile b/Dockerfile
index ce0023f..2095687 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -19,7 +19,7 @@ ENV DOTNET_ENVIRONMENT=${ENVIRONMENT}
WORKDIR /sln
# Dotnet Restore
-COPY ./*.sln ./NuGet.config ./Directory.Build.props ./
+COPY ./*.sln ./NuGet.config ./Directory.Build.props ./Directory.Packages.props ./
COPY src/*/*.csproj ./
RUN for file in $(ls *.csproj); do mkdir -p src/${file%.*}/ && mv $file src/${file%.*}/; done
COPY tests/*/*.csproj ./
@@ -35,7 +35,7 @@ RUN dotnet build --no-restore -c Release -v minimal -p:VersionPrefix=${VERSION_P
# Dotnet Test
FROM build AS test
-RUN dotnet test --no-restore --no-build -c Release -v minimal -p:CollectCoverage=true -p:CoverletOutput=../results/ -p:MergeWith="../results/coverage.json" -p:CoverletOutputFormat=opencover%2cjson -m:1 -p:ExcludeByFile="**/Program.cs"
+RUN dotnet test --no-restore --no-build -c Release -v minimal -p:CollectCoverage=true -p:CoverletOutput=../results/ -p:MergeWith="../results/coverage.json" -p:CoverletOutputFormat=opencover%2cjson -m:1 -p:ExcludeByFile="**/Program.cs%2c**/Migrations/*.cs"
FROM scratch AS coverage
COPY --from=test /sln/tests/results/*.xml .
@@ -48,7 +48,15 @@ RUN dotnet publish ./src/**/Presentation.csproj --no-restore -c Release -v quiet
# Runtime Image
FROM ${BASE_IMAGE_REPO}/${BASE_IMAGE_RUNTIME}:${BASE_IMAGE_RUNTIME_TAG} AS run
-WORKDIR /
+WORKDIR /app
EXPOSE 8080
COPY --from=publish /sln/app .
+
+# The database lives in /app/data, the only folder the non-root app user can write to.
+RUN mkdir -p /app/data && chown $APP_UID /app/data
+USER $APP_UID
+
+HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
+ CMD wget -qO- http://localhost:8080/health/live || exit 1
+
ENTRYPOINT ["dotnet", "Presentation.dll"]
diff --git a/README.md b/README.md
index 9434071..400b979 100644
--- a/README.md
+++ b/README.md
@@ -87,7 +87,7 @@ The one deliberate break from Clean Architecture is that the Presentation projec
- Six task-shaped tools (`movies_search`, `movies_get`, `authors_search`, `reviews_list`, `reviews_write`, `reviews_delete`) with titles, read-only, destructive and idempotent hints, and descriptions written for agents
- Resources for each movie, author and review (`movies://{movieId}`, `authors://{authorId}`, `reviews://{reviewId}`) and the server version (`server://version`)
- Prompts for common jobs (`summarise_movie_reception`, `compare_movies`, `review_movie`) that embed the movies they're about, with completions that suggest movie titles and author names as you type
-- Search with paging and small results by default: every list returns 10 items, a total count and a cursor, with names and average ratings next to ids
+- Search with paging and small results by default: every list returns 10 items, a total count and the offset of the next page, with names and average ratings next to ids
- Optional OAuth protection for `/mcp`: JWT bearer tokens plus MCP protected resource metadata, turned on by setting an authority
- Logging using [Serilog](https://github.com/serilog/serilog), with [Seq](https://datalust.co/seq) when running in Docker
- Mediator pattern using [Mediator](https://github.com/martinothamar/Mediator)
@@ -95,10 +95,13 @@ The one deliberate break from Clean Architecture is that the Presentation projec
- Typed tool results published with an output schema and returned as structured content as well as JSON text
- Errors mapped from Application exceptions by request filters: tool errors tell the agent how to recover, and resources and prompts return MCP protocol errors such as resource not found
- Object mapping using [Mapperly](https://mapperly.riok.app)
-- In-memory data using [Entity Framework Core](https://learn.microsoft.com/ef/core/providers/in-memory/) seeded with [Bogus](https://github.com/bchavez/Bogus)
+- Data stored in [SQLite](https://learn.microsoft.com/ef/core/providers/sqlite/) using [Entity Framework Core](https://learn.microsoft.com/ef/core) migrations, seeded with [Bogus](https://github.com/bchavez/Bogus) only when `Database:SeedSampleData` is on. Each test uses its own throwaway in-memory SQLite database, so tests never touch a real one or each other's data
- Testing using [xUnit](https://xunit.net), [Shouldly](https://github.com/shouldly/shouldly) and [NSubstitute](https://github.com/nsubstitute/NSubstitute), with coverage from [Coverlet](https://github.com/coverlet-coverage/coverlet)
-- CI with GitHub Actions: build and test, 95% coverage gate, [Trivy](https://trivy.dev) container scan, [CodeQL](https://codeql.github.com) static analysis, then NuGet publishing and a GitHub release from `main` using [trusted publishing](https://learn.microsoft.com/nuget/nuget-org/trusted-publishing)
-- Monthly grouped dependency updates using [Dependabot](https://docs.github.com/code-security/dependabot)
+- Build rules in `Directory.Build.props`: code style and the recommended analyzers are checked on every build, warnings fail it, and package versions live in one place with [Central Package Management](https://learn.microsoft.com/nuget/consume-packages/central-package-management)
+- CI with GitHub Actions: build and test, a `dotnet format` check, 95% coverage gate, [Trivy](https://trivy.dev) container scan, [CodeQL](https://codeql.github.com) static analysis, then NuGet publishing and a GitHub release from `main` using [trusted publishing](https://learn.microsoft.com/nuget/nuget-org/trusted-publishing)
+- Health checks at `/health/live` and `/health/ready`, using [ASP.NET Core health checks](https://learn.microsoft.com/aspnet/core/host-and-deploy/health-checks)
+- Monthly grouped dependency updates using [Dependabot](https://docs.github.com/code-security/dependabot), including the pinned Seq image
+- A Docker image that runs as a non-root user with a health check
## Related templates
diff --git a/docker-compose.yml b/docker-compose.yml
index 7f5267a..051a3b7 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -10,6 +10,8 @@ services:
- "8080:8080"
environment:
DOTNET_ENVIRONMENT: docker
+ volumes:
+ - movie-reviews-data:/app/data
networks:
- cleanmodelcontextprotocol_network
depends_on:
@@ -24,7 +26,7 @@ services:
depends_on:
- api
seq:
- image: datalust/seq:latest
+ image: datalust/seq:2026.1.17473
ports:
- "5341:80"
environment:
@@ -32,6 +34,8 @@ services:
SEQ_FIRSTRUN_NOAUTHENTICATION: "true"
networks:
- cleanmodelcontextprotocol_network
+volumes:
+ movie-reviews-data:
networks:
cleanmodelcontextprotocol_network:
driver: bridge
diff --git a/docs/RUN.md b/docs/RUN.md
index 9ee7f48..4db89c6 100644
--- a/docs/RUN.md
+++ b/docs/RUN.md
@@ -2,6 +2,17 @@
There are two pre-configured environments, `local` and `docker`. The matching `appsettings.*.json` files decide where logs go: the console when running locally, and a [Seq](https://datalust.co/seq) container when running in Docker.
+## Database
+
+The app stores its data in a SQLite file, `movie-reviews.db`, next to the app. In Docker the file is `/app/data/movie-reviews.db`, on the `movie-reviews-data` volume, so it survives a restart. On startup the app applies any pending Entity Framework Core migrations. When `Database:SeedSampleData` is `true`, it also seeds the same sample data into an empty database. It's on in `appsettings.local.json` and `appsettings.docker.json` and off everywhere else, so a deployed copy never starts with fake data. Delete the file, or run `docker compose down -v`, to start again. Change `ConnectionStrings:MovieReviews` to point somewhere else, or to `Data Source=MovieReviews;Mode=Memory;Cache=Shared` to keep everything in memory.
+
+To add a migration after changing the data model:
+
+``` bash
+dotnet tool install --global dotnet-ef
+dotnet ef migrations add --project ./src/Infrastructure --output-dir Databases/MovieReviews/Migrations
+```
+
## .NET CLI
`launchSettings.json` sets the ports, environment and logging, so one command is enough.
@@ -21,6 +32,9 @@ docker compose up -d --build
- App: (MCP endpoint, Streamable HTTP)
- MCP Inspector: . Flip the switch on the server card to connect, then open **Tools** to see every tool with its description and input schema and run it.
- Seq:
+- Health checks: (the process is up) and (the database can be reached). Both answer without a token. The image's `HEALTHCHECK` uses the live one.
+
+The container runs as the image's non-root `app` user.
To shut the containers down:
@@ -28,8 +42,14 @@ To shut the containers down:
docker compose down
```
+## HTTPS
+
+Outside the `local` and `Development` environments the app sends an HSTS header and redirects HTTP to HTTPS. The container only listens on HTTP, so in production put it behind a proxy or load balancer that ends TLS, and set `ASPNETCORE_FORWARDEDHEADERS_ENABLED=true` so the app knows the original request was HTTPS.
+
## Tests
``` bash
dotnet test
```
+
+The tests never touch `movie-reviews.db`. Each test builds its own in-memory SQLite database from the migrations and the same fixed seed, so no test can change what another one sees and the results are the same every time.
diff --git a/src/Application/Application.csproj b/src/Application/Application.csproj
index b16faf7..354c1cd 100644
--- a/src/Application/Application.csproj
+++ b/src/Application/Application.csproj
@@ -2,13 +2,11 @@
false
- true
- $(NoWarn);1591
-
-
+
+
diff --git a/src/Application/Authors/Entities/Author.cs b/src/Application/Authors/Entities/Author.cs
index c3d93e4..a7ada1e 100644
--- a/src/Application/Authors/Entities/Author.cs
+++ b/src/Application/Authors/Entities/Author.cs
@@ -9,4 +9,4 @@ namespace CleanModelContextProtocol.Application.Authors.Entities;
/// The author's first name.
/// The author's last name.
/// The reviews the author has written.
-public record Author(Guid Id, string FirstName, string LastName, ICollection Reviews = null);
+public record Author(Guid Id, string FirstName, string LastName, ICollection Reviews);
diff --git a/src/Application/Authors/Entities/AuthorSummary.cs b/src/Application/Authors/Entities/AuthorSummary.cs
new file mode 100644
index 0000000..7110532
--- /dev/null
+++ b/src/Application/Authors/Entities/AuthorSummary.cs
@@ -0,0 +1,11 @@
+namespace CleanModelContextProtocol.Application.Authors.Entities;
+
+///
+/// An author in a list, with how many reviews they have written and their average star rating instead of the reviews themselves.
+///
+/// The unique identifier of the author.
+/// The author's first name.
+/// The author's last name.
+/// The number of reviews the author has written.
+/// The average star rating the author gives to one decimal place, or null when they have no reviews.
+public record AuthorSummary(Guid Id, string FirstName, string LastName, int ReviewCount, double? AverageStars);
diff --git a/src/Application/Authors/IAuthorsRepository.cs b/src/Application/Authors/IAuthorsRepository.cs
index b1ae1e7..6225772 100644
--- a/src/Application/Authors/IAuthorsRepository.cs
+++ b/src/Application/Authors/IAuthorsRepository.cs
@@ -1,19 +1,16 @@
namespace CleanModelContextProtocol.Application.Authors;
-using System.Threading.Tasks;
using Entities;
public interface IAuthorsRepository
{
- public Task> GetAuthors(CancellationToken cancellationToken);
-
- public Task GetAuthorById(Guid id, CancellationToken cancellationToken);
-
- public Task AuthorExists(Guid id, CancellationToken cancellationToken);
-
- public Task<(List Items, int TotalCount)> SearchAuthors(
- string query,
+ public Task<(List Items, int TotalCount)> GetAuthors(
+ string? query,
int offset,
int limit,
CancellationToken cancellationToken);
+
+ public Task GetAuthorById(Guid id, CancellationToken cancellationToken);
+
+ public Task AuthorExists(Guid id, CancellationToken cancellationToken);
}
diff --git a/src/Application/Authors/Queries/GetAuthors/GetAuthorsHandler.cs b/src/Application/Authors/Queries/GetAuthors/GetAuthorsHandler.cs
index 00af4f7..27add67 100644
--- a/src/Application/Authors/Queries/GetAuthors/GetAuthorsHandler.cs
+++ b/src/Application/Authors/Queries/GetAuthors/GetAuthorsHandler.cs
@@ -1,14 +1,15 @@
namespace CleanModelContextProtocol.Application.Authors.Queries.GetAuthors;
-using System.Threading;
-using System.Threading.Tasks;
+using Common.Paging;
using Entities;
using Mediator;
-public class GetAuthorsHandler(IAuthorsRepository repository) : IRequestHandler>
+public class GetAuthorsHandler(IAuthorsRepository repository) : IRequestHandler>
{
- public async ValueTask> Handle(GetAuthorsQuery request, CancellationToken cancellationToken)
+ public async ValueTask> Handle(GetAuthorsQuery request, CancellationToken cancellationToken)
{
- return await repository.GetAuthors(cancellationToken);
+ var (items, totalCount) = await repository.GetAuthors(request.Query, request.Offset, request.Limit, cancellationToken);
+
+ return new Page(items, request.Offset, request.Limit, totalCount);
}
}
diff --git a/src/Application/Authors/Queries/GetAuthors/GetAuthorsQuery.cs b/src/Application/Authors/Queries/GetAuthors/GetAuthorsQuery.cs
index fa23471..3953b11 100644
--- a/src/Application/Authors/Queries/GetAuthors/GetAuthorsQuery.cs
+++ b/src/Application/Authors/Queries/GetAuthors/GetAuthorsQuery.cs
@@ -1,8 +1,21 @@
namespace CleanModelContextProtocol.Application.Authors.Queries.GetAuthors;
+using Common.Paging;
using Entities;
using Mediator;
-public class GetAuthorsQuery : IRequest>
+///
+/// Lists authors one page at a time, optionally only those whose name contains a search term. Each author comes with
+/// their review count and average stars rather than their reviews, which returns.
+///
+public class GetAuthorsQuery : IRequest>
{
+ /// The words to look for in the first, last or full name, ignoring case. Leave empty to list every author.
+ public string? Query { get; init; }
+
+ /// The number of results to skip, 0 for the first page.
+ public int Offset { get; init; }
+
+ /// The largest number of results to return, from 1 to 50.
+ public int Limit { get; init; } = Paging.DefaultLimit;
}
diff --git a/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsValidator.cs b/src/Application/Authors/Queries/GetAuthors/GetAuthorsValidator.cs
similarity index 56%
rename from src/Application/Authors/Queries/SearchAuthors/SearchAuthorsValidator.cs
rename to src/Application/Authors/Queries/GetAuthors/GetAuthorsValidator.cs
index 0d258c2..5509117 100644
--- a/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsValidator.cs
+++ b/src/Application/Authors/Queries/GetAuthors/GetAuthorsValidator.cs
@@ -1,14 +1,14 @@
-namespace CleanModelContextProtocol.Application.Authors.Queries.SearchAuthors;
+namespace CleanModelContextProtocol.Application.Authors.Queries.GetAuthors;
using Common.Paging;
using FluentValidation;
-public class SearchAuthorsValidator : AbstractValidator
+public class GetAuthorsValidator : AbstractValidator
{
- public SearchAuthorsValidator()
+ public GetAuthorsValidator()
{
_ = this.RuleFor(r => r.Query).ValidSearchTerm();
+ _ = this.RuleFor(r => r.Offset).ValidOffset();
_ = this.RuleFor(r => r.Limit).ValidLimit();
- _ = this.RuleFor(r => r.Cursor).ValidCursor();
}
}
diff --git a/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsHandler.cs b/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsHandler.cs
deleted file mode 100644
index 8af794c..0000000
--- a/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsHandler.cs
+++ /dev/null
@@ -1,19 +0,0 @@
-namespace CleanModelContextProtocol.Application.Authors.Queries.SearchAuthors;
-
-using System.Threading;
-using System.Threading.Tasks;
-using Common.Paging;
-using Entities;
-using Mediator;
-
-public class SearchAuthorsHandler(IAuthorsRepository repository) : IRequestHandler>
-{
- public async ValueTask> Handle(SearchAuthorsQuery request, CancellationToken cancellationToken)
- {
- _ = Paging.TryDecode(request.Cursor, out var offset);
-
- var (items, totalCount) = await repository.SearchAuthors(request.Query, offset, request.Limit, cancellationToken);
-
- return Paging.ToPage(items, totalCount, offset);
- }
-}
diff --git a/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsQuery.cs b/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsQuery.cs
deleted file mode 100644
index a3c12f7..0000000
--- a/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsQuery.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-namespace CleanModelContextProtocol.Application.Authors.Queries.SearchAuthors;
-
-using Common.Paging;
-using Entities;
-using Mediator;
-
-///
-/// Finds authors whose the first or last name contains a search term, one page at a time.
-///
-public class SearchAuthorsQuery : IRequest>
-{
- /// The words to look for, ignoring case. Leave empty to list every one.
- public string Query { get; init; }
-
- /// The largest number of results to return, from 1 to 50.
- public int Limit { get; init; } = Paging.DefaultLimit;
-
- /// The cursor from a previous page, or empty for the first page.
- public string Cursor { get; init; }
-}
diff --git a/src/Application/Common/Exceptions/NotFoundException.cs b/src/Application/Common/Exceptions/NotFoundException.cs
index 196ccec..57cbe7d 100644
--- a/src/Application/Common/Exceptions/NotFoundException.cs
+++ b/src/Application/Common/Exceptions/NotFoundException.cs
@@ -1,6 +1,7 @@
namespace CleanModelContextProtocol.Application.Common.Exceptions;
using System;
+using System.Diagnostics.CodeAnalysis;
using Enums;
public class NotFoundException(string message) : Exception(message)
@@ -8,7 +9,7 @@ public class NotFoundException(string message) : Exception(message)
/// Throws a if is null.
/// The reference type argument to validate as non-null.
/// The entity type of the parameter.
- public static void ThrowIfNull(object argument, EntityType entityType)
+ public static void ThrowIfNull([NotNull] object? argument, EntityType entityType)
{
if (argument is null)
{
@@ -18,6 +19,7 @@ public static void ThrowIfNull(object argument, EntityType entityType)
/// Throws a
/// The entity type that was not found.
+ [DoesNotReturn]
public static void Throw(EntityType entityType)
{
throw new NotFoundException($"The {entityType} with the supplied id was not found.");
diff --git a/src/Application/Common/Paging/Page.cs b/src/Application/Common/Paging/Page.cs
index 776cc83..e01132a 100644
--- a/src/Application/Common/Paging/Page.cs
+++ b/src/Application/Common/Paging/Page.cs
@@ -1,10 +1,11 @@
namespace CleanModelContextProtocol.Application.Common.Paging;
///
-/// One page of results from a search.
+/// One page of results from a list.
///
/// The type of the results.
/// The results on this page.
+/// The number of results skipped before this page.
+/// The largest number of results this page could hold.
/// The number of results across every page.
-/// The cursor that fetches the next page, or null when this is the last page.
-public record Page(List Items, int TotalCount, string NextCursor = null);
+public record Page(List Items, int Offset, int Limit, int TotalCount);
diff --git a/src/Application/Common/Paging/Paging.cs b/src/Application/Common/Paging/Paging.cs
index 440b9e2..e6aa4bc 100644
--- a/src/Application/Common/Paging/Paging.cs
+++ b/src/Application/Common/Paging/Paging.cs
@@ -1,10 +1,7 @@
namespace CleanModelContextProtocol.Application.Common.Paging;
-using System.Globalization;
-using System.Text;
-
///
-/// Limits and opaque cursors shared by every search.
+/// The limits shared by every paged list.
///
public static class Paging
{
@@ -13,53 +10,4 @@ public static class Paging
/// The largest number of results a single page can return.
public const int MaxLimit = 50;
-
- private const string Prefix = "offset:";
-
- /// Creates the cursor for the page that starts at .
- /// The number of results to skip.
- /// An opaque cursor.
- public static string Encode(int offset)
- {
- return Convert.ToBase64String(Encoding.UTF8.GetBytes(Prefix + offset.ToString(CultureInfo.InvariantCulture)));
- }
-
- /// Reads the offset from a cursor. An empty cursor is the first page.
- /// The cursor from a previous page, or null for the first page.
- /// The number of results to skip.
- /// True when the cursor is empty or valid.
- public static bool TryDecode(string cursor, out int offset)
- {
- offset = 0;
-
- if (string.IsNullOrEmpty(cursor))
- {
- return true;
- }
-
- try
- {
- var value = Encoding.UTF8.GetString(Convert.FromBase64String(cursor));
-
- return value.StartsWith(Prefix, StringComparison.Ordinal)
- && int.TryParse(value.AsSpan(Prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out offset);
- }
- catch (FormatException)
- {
- return false;
- }
- }
-
- /// Creates the page for a set of results, with a cursor when more results remain.
- /// The type of the results.
- /// The results on this page.
- /// The number of results across every page.
- /// The number of results skipped before this page.
- /// The page.
- public static Page ToPage(List items, int totalCount, int offset)
- {
- var next = offset + items.Count;
-
- return new Page(items, totalCount, next < totalCount ? Encode(next) : null);
- }
}
diff --git a/src/Application/Common/Paging/PagingValidatorExtensions.cs b/src/Application/Common/Paging/PagingValidatorExtensions.cs
index 940bb27..040ba78 100644
--- a/src/Application/Common/Paging/PagingValidatorExtensions.cs
+++ b/src/Application/Common/Paging/PagingValidatorExtensions.cs
@@ -3,34 +3,33 @@ namespace CleanModelContextProtocol.Application.Common.Paging;
using FluentValidation;
///
-/// Validation rules shared by every search.
+/// Validation rules shared by every paged list.
///
public static class PagingValidatorExtensions
{
- /// Checks that a limit is between 1 and .
+ /// Checks that an offset is zero or more.
/// The type being validated.
- /// The rule for the limit.
+ /// The rule for the offset.
/// The rule.
- public static IRuleBuilderOptions ValidLimit(this IRuleBuilder rule)
+ public static IRuleBuilderOptions ValidOffset(this IRuleBuilder rule)
{
- return rule.InclusiveBetween(1, Paging.MaxLimit).WithMessage($"A limit must be between 1 and {Paging.MaxLimit}.");
+ return rule.GreaterThanOrEqualTo(0).WithMessage("An offset can't be negative. Use 0 for the first page.");
}
- /// Checks that a cursor is empty or came from a previous page.
+ /// Checks that a limit is between 1 and .
/// The type being validated.
- /// The rule for the cursor.
+ /// The rule for the limit.
/// The rule.
- public static IRuleBuilderOptions ValidCursor(this IRuleBuilder rule)
+ public static IRuleBuilderOptions ValidLimit(this IRuleBuilder rule)
{
- return rule.Must(cursor => Paging.TryDecode(cursor, out _))
- .WithMessage("The cursor is not valid. Use the nextCursor from a previous page, or leave it empty for the first page.");
+ return rule.InclusiveBetween(1, Paging.MaxLimit).WithMessage($"A limit must be between 1 and {Paging.MaxLimit}.");
}
/// Checks that a search term is no longer than 100 characters.
/// The type being validated.
/// The rule for the search term.
/// The rule.
- public static IRuleBuilderOptions ValidSearchTerm(this IRuleBuilder rule)
+ public static IRuleBuilderOptions ValidSearchTerm(this IRuleBuilder rule)
{
return rule.MaximumLength(100).WithMessage("A search term can't be longer than 100 characters.");
}
diff --git a/src/Application/Movies/Entities/Movie.cs b/src/Application/Movies/Entities/Movie.cs
index a664863..1f3ee83 100644
--- a/src/Application/Movies/Entities/Movie.cs
+++ b/src/Application/Movies/Entities/Movie.cs
@@ -8,4 +8,4 @@ namespace CleanModelContextProtocol.Application.Movies.Entities;
/// The unique identifier of the movie.
/// The title of the movie.
/// The reviews written about the movie.
-public record Movie(Guid Id, string Title, ICollection Reviews = null);
+public record Movie(Guid Id, string Title, ICollection Reviews);
diff --git a/src/Application/Movies/Entities/MovieSummary.cs b/src/Application/Movies/Entities/MovieSummary.cs
new file mode 100644
index 0000000..cc7f8cf
--- /dev/null
+++ b/src/Application/Movies/Entities/MovieSummary.cs
@@ -0,0 +1,10 @@
+namespace CleanModelContextProtocol.Application.Movies.Entities;
+
+///
+/// A movie in a list, with how many reviews it has and their average star rating instead of the reviews themselves.
+///
+/// The unique identifier of the movie.
+/// The title of the movie.
+/// The number of reviews written about the movie.
+/// The average star rating to one decimal place, or null when the movie has no reviews.
+public record MovieSummary(Guid Id, string Title, int ReviewCount, double? AverageStars);
diff --git a/src/Application/Movies/IMoviesRepository.cs b/src/Application/Movies/IMoviesRepository.cs
index eb55f94..46a5ac1 100644
--- a/src/Application/Movies/IMoviesRepository.cs
+++ b/src/Application/Movies/IMoviesRepository.cs
@@ -1,19 +1,16 @@
namespace CleanModelContextProtocol.Application.Movies;
-using System.Threading.Tasks;
using Entities;
public interface IMoviesRepository
{
- public Task> GetMovies(CancellationToken cancellationToken);
-
- public Task GetMovieById(Guid id, CancellationToken cancellationToken);
-
- public Task MovieExists(Guid id, CancellationToken cancellationToken);
-
- public Task<(List Items, int TotalCount)> SearchMovies(
- string query,
+ public Task<(List Items, int TotalCount)> GetMovies(
+ string? query,
int offset,
int limit,
CancellationToken cancellationToken);
+
+ public Task GetMovieById(Guid id, CancellationToken cancellationToken);
+
+ public Task MovieExists(Guid id, CancellationToken cancellationToken);
}
diff --git a/src/Application/Movies/Queries/GetMovies/GetMoviesHandler.cs b/src/Application/Movies/Queries/GetMovies/GetMoviesHandler.cs
index 81488e2..46a47e9 100644
--- a/src/Application/Movies/Queries/GetMovies/GetMoviesHandler.cs
+++ b/src/Application/Movies/Queries/GetMovies/GetMoviesHandler.cs
@@ -1,14 +1,15 @@
namespace CleanModelContextProtocol.Application.Movies.Queries.GetMovies;
-using System.Threading;
-using System.Threading.Tasks;
+using Common.Paging;
using Entities;
using Mediator;
-public class GetMoviesHandler(IMoviesRepository repository) : IRequestHandler>
+public class GetMoviesHandler(IMoviesRepository repository) : IRequestHandler>
{
- public async ValueTask> Handle(GetMoviesQuery request, CancellationToken cancellationToken)
+ public async ValueTask> Handle(GetMoviesQuery request, CancellationToken cancellationToken)
{
- return await repository.GetMovies(cancellationToken);
+ var (items, totalCount) = await repository.GetMovies(request.Query, request.Offset, request.Limit, cancellationToken);
+
+ return new Page(items, request.Offset, request.Limit, totalCount);
}
}
diff --git a/src/Application/Movies/Queries/GetMovies/GetMoviesQuery.cs b/src/Application/Movies/Queries/GetMovies/GetMoviesQuery.cs
index 03a644c..2d4b460 100644
--- a/src/Application/Movies/Queries/GetMovies/GetMoviesQuery.cs
+++ b/src/Application/Movies/Queries/GetMovies/GetMoviesQuery.cs
@@ -1,8 +1,21 @@
namespace CleanModelContextProtocol.Application.Movies.Queries.GetMovies;
+using Common.Paging;
using Entities;
using Mediator;
-public class GetMoviesQuery : IRequest>
+///
+/// Lists movies one page at a time, optionally only those whose title contains a search term. Each movie comes with its
+/// review count and average stars rather than its reviews, which returns.
+///
+public class GetMoviesQuery : IRequest>
{
+ /// The words to look for in the title, ignoring case. Leave empty to list every movie.
+ public string? Query { get; init; }
+
+ /// The number of results to skip, 0 for the first page.
+ public int Offset { get; init; }
+
+ /// The largest number of results to return, from 1 to 50.
+ public int Limit { get; init; } = Paging.DefaultLimit;
}
diff --git a/src/Application/Movies/Queries/GetMovies/GetMoviesValidator.cs b/src/Application/Movies/Queries/GetMovies/GetMoviesValidator.cs
new file mode 100644
index 0000000..883d8f7
--- /dev/null
+++ b/src/Application/Movies/Queries/GetMovies/GetMoviesValidator.cs
@@ -0,0 +1,14 @@
+namespace CleanModelContextProtocol.Application.Movies.Queries.GetMovies;
+
+using Common.Paging;
+using FluentValidation;
+
+public class GetMoviesValidator : AbstractValidator
+{
+ public GetMoviesValidator()
+ {
+ _ = this.RuleFor(r => r.Query).ValidSearchTerm();
+ _ = this.RuleFor(r => r.Offset).ValidOffset();
+ _ = this.RuleFor(r => r.Limit).ValidLimit();
+ }
+}
diff --git a/src/Application/Movies/Queries/SearchMovies/SearchMoviesHandler.cs b/src/Application/Movies/Queries/SearchMovies/SearchMoviesHandler.cs
deleted file mode 100644
index 2486af7..0000000
--- a/src/Application/Movies/Queries/SearchMovies/SearchMoviesHandler.cs
+++ /dev/null
@@ -1,19 +0,0 @@
-namespace CleanModelContextProtocol.Application.Movies.Queries.SearchMovies;
-
-using System.Threading;
-using System.Threading.Tasks;
-using Common.Paging;
-using Entities;
-using Mediator;
-
-public class SearchMoviesHandler(IMoviesRepository repository) : IRequestHandler>
-{
- public async ValueTask> Handle(SearchMoviesQuery request, CancellationToken cancellationToken)
- {
- _ = Paging.TryDecode(request.Cursor, out var offset);
-
- var (items, totalCount) = await repository.SearchMovies(request.Query, offset, request.Limit, cancellationToken);
-
- return Paging.ToPage(items, totalCount, offset);
- }
-}
diff --git a/src/Application/Movies/Queries/SearchMovies/SearchMoviesQuery.cs b/src/Application/Movies/Queries/SearchMovies/SearchMoviesQuery.cs
deleted file mode 100644
index 39be8fa..0000000
--- a/src/Application/Movies/Queries/SearchMovies/SearchMoviesQuery.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-namespace CleanModelContextProtocol.Application.Movies.Queries.SearchMovies;
-
-using Common.Paging;
-using Entities;
-using Mediator;
-
-///
-/// Finds movies whose the title contains a search term, one page at a time.
-///
-public class SearchMoviesQuery : IRequest>
-{
- /// The words to look for, ignoring case. Leave empty to list every one.
- public string Query { get; init; }
-
- /// The largest number of results to return, from 1 to 50.
- public int Limit { get; init; } = Paging.DefaultLimit;
-
- /// The cursor from a previous page, or empty for the first page.
- public string Cursor { get; init; }
-}
diff --git a/src/Application/Movies/Queries/SearchMovies/SearchMoviesValidator.cs b/src/Application/Movies/Queries/SearchMovies/SearchMoviesValidator.cs
deleted file mode 100644
index d45bca5..0000000
--- a/src/Application/Movies/Queries/SearchMovies/SearchMoviesValidator.cs
+++ /dev/null
@@ -1,14 +0,0 @@
-namespace CleanModelContextProtocol.Application.Movies.Queries.SearchMovies;
-
-using Common.Paging;
-using FluentValidation;
-
-public class SearchMoviesValidator : AbstractValidator
-{
- public SearchMoviesValidator()
- {
- _ = this.RuleFor(r => r.Query).ValidSearchTerm();
- _ = this.RuleFor(r => r.Limit).ValidLimit();
- _ = this.RuleFor(r => r.Cursor).ValidCursor();
- }
-}
diff --git a/src/Application/Reviews/Commands/UpdateReview/UpdateReviewCommand.cs b/src/Application/Reviews/Commands/UpdateReview/UpdateReviewCommand.cs
index 0f11c5d..2ba0410 100644
--- a/src/Application/Reviews/Commands/UpdateReview/UpdateReviewCommand.cs
+++ b/src/Application/Reviews/Commands/UpdateReview/UpdateReviewCommand.cs
@@ -2,13 +2,14 @@ namespace CleanModelContextProtocol.Application.Reviews.Commands.UpdateReview;
using Mediator;
+///
+/// Changes the star rating of a review. The author and the movie of a review can't change.
+///
public class UpdateReviewCommand : IRequest
{
- public Guid Id { get; set; }
-
- public Guid AuthorId { get; init; }
-
- public Guid MovieId { get; init; }
+ /// The unique identifier of the review.
+ public Guid Id { get; init; }
+ /// The new star rating, from 1 to 5.
public int Stars { get; init; }
}
diff --git a/src/Application/Reviews/Commands/UpdateReview/UpdateReviewHandler.cs b/src/Application/Reviews/Commands/UpdateReview/UpdateReviewHandler.cs
index 90b07f3..7e9dedc 100644
--- a/src/Application/Reviews/Commands/UpdateReview/UpdateReviewHandler.cs
+++ b/src/Application/Reviews/Commands/UpdateReview/UpdateReviewHandler.cs
@@ -1,17 +1,10 @@
namespace CleanModelContextProtocol.Application.Reviews.Commands.UpdateReview;
-using System.Threading;
-using System.Threading.Tasks;
-using CleanModelContextProtocol.Application.Authors;
-using CleanModelContextProtocol.Application.Movies;
using Common.Enums;
using Common.Exceptions;
using Mediator;
-public class UpdateReviewHandler(
- IAuthorsRepository authorsRepository,
- IMoviesRepository moviesRepository,
- IReviewsRepository reviewsRepository) : IRequestHandler
+public class UpdateReviewHandler(IReviewsRepository reviewsRepository) : IRequestHandler
{
public async ValueTask Handle(UpdateReviewCommand request, CancellationToken cancellationToken)
{
@@ -20,17 +13,6 @@ public async ValueTask Handle(UpdateReviewCommand request, CancellationTok
NotFoundException.Throw(EntityType.Review);
}
- if (!await authorsRepository.AuthorExists(request.AuthorId, cancellationToken))
- {
- NotFoundException.Throw(EntityType.Author);
- }
-
- if (!await moviesRepository.MovieExists(request.MovieId, cancellationToken))
- {
- NotFoundException.Throw(EntityType.Movie);
- }
-
- return await reviewsRepository
- .UpdateReview(request.Id, request.AuthorId, request.MovieId, request.Stars, cancellationToken);
+ return await reviewsRepository.UpdateReview(request.Id, request.Stars, cancellationToken);
}
}
diff --git a/src/Application/Reviews/Commands/UpdateReview/UpdateReviewValidator.cs b/src/Application/Reviews/Commands/UpdateReview/UpdateReviewValidator.cs
index d95b20f..a1bb7b1 100644
--- a/src/Application/Reviews/Commands/UpdateReview/UpdateReviewValidator.cs
+++ b/src/Application/Reviews/Commands/UpdateReview/UpdateReviewValidator.cs
@@ -7,8 +7,6 @@ public class UpdateReviewValidator : AbstractValidator
public UpdateReviewValidator()
{
_ = this.RuleFor(r => r.Id).NotEqual(Guid.Empty).WithMessage("A review id was not supplied to Update the review.");
- _ = this.RuleFor(r => r.AuthorId).NotEqual(Guid.Empty).WithMessage("An author id was not supplied to Update the review.");
- _ = this.RuleFor(r => r.MovieId).NotEqual(Guid.Empty).WithMessage("A movie id was not supplied to Update the review.");
_ = this.RuleFor(r => r.Stars).InclusiveBetween(1, 5).WithMessage("A star rating must be between 1 and 5.");
}
}
diff --git a/src/Application/Reviews/Entities/Review.cs b/src/Application/Reviews/Entities/Review.cs
index 580814e..da115ce 100644
--- a/src/Application/Reviews/Entities/Review.cs
+++ b/src/Application/Reviews/Entities/Review.cs
@@ -13,5 +13,5 @@ namespace CleanModelContextProtocol.Application.Reviews.Entities;
public record Review(
Guid Id,
int Stars,
- ReviewedMovie ReviewedMovie = null,
- ReviewAuthor ReviewAuthor = null);
+ ReviewedMovie? ReviewedMovie = null,
+ ReviewAuthor? ReviewAuthor = null);
diff --git a/src/Application/Reviews/IReviewsRepository.cs b/src/Application/Reviews/IReviewsRepository.cs
index 1e59e60..cf1781e 100644
--- a/src/Application/Reviews/IReviewsRepository.cs
+++ b/src/Application/Reviews/IReviewsRepository.cs
@@ -1,6 +1,5 @@
namespace CleanModelContextProtocol.Application.Reviews;
-using System.Threading.Tasks;
using Entities;
public interface IReviewsRepository
@@ -13,23 +12,20 @@ public Task CreateReview(
public Task DeleteReview(Guid id, CancellationToken cancellationToken);
- public Task> GetReviews(CancellationToken cancellationToken);
-
- public Task GetReviewById(Guid id, CancellationToken cancellationToken);
-
- public Task ReviewExists(Guid id, CancellationToken cancellationToken);
-
- public Task<(List Items, int TotalCount)> SearchReviews(
+ public Task<(List Items, int TotalCount)> GetReviews(
Guid? movieId,
Guid? authorId,
int offset,
int limit,
CancellationToken cancellationToken);
- public Task UpdateReview(
- Guid id,
- Guid authorId,
- Guid movieId,
- int stars,
- CancellationToken cancellationToken);
+ public Task> GetReviewsForMovies(IReadOnlyCollection movieIds, CancellationToken cancellationToken);
+
+ public Task> GetReviewsForAuthors(IReadOnlyCollection authorIds, CancellationToken cancellationToken);
+
+ public Task GetReviewById(Guid id, CancellationToken cancellationToken);
+
+ public Task ReviewExists(Guid id, CancellationToken cancellationToken);
+
+ public Task UpdateReview(Guid id, int stars, CancellationToken cancellationToken);
}
diff --git a/src/Application/Reviews/Queries/GetReviews/GetReviewsHandler.cs b/src/Application/Reviews/Queries/GetReviews/GetReviewsHandler.cs
index fc0c1a9..e46086e 100644
--- a/src/Application/Reviews/Queries/GetReviews/GetReviewsHandler.cs
+++ b/src/Application/Reviews/Queries/GetReviews/GetReviewsHandler.cs
@@ -1,14 +1,15 @@
namespace CleanModelContextProtocol.Application.Reviews.Queries.GetReviews;
-using System.Threading;
-using System.Threading.Tasks;
+using Common.Paging;
using Entities;
using Mediator;
-public class GetReviewsHandler(IReviewsRepository repository) : IRequestHandler>
+public class GetReviewsHandler(IReviewsRepository repository) : IRequestHandler>
{
- public async ValueTask> Handle(GetReviewsQuery request, CancellationToken cancellationToken)
+ public async ValueTask> Handle(GetReviewsQuery request, CancellationToken cancellationToken)
{
- return await repository.GetReviews(cancellationToken);
+ var (items, totalCount) = await repository.GetReviews(request.MovieId, request.AuthorId, request.Offset, request.Limit, cancellationToken);
+
+ return new Page(items, request.Offset, request.Limit, totalCount);
}
}
diff --git a/src/Application/Reviews/Queries/GetReviews/GetReviewsQuery.cs b/src/Application/Reviews/Queries/GetReviews/GetReviewsQuery.cs
index 23c80bc..6e735bd 100644
--- a/src/Application/Reviews/Queries/GetReviews/GetReviewsQuery.cs
+++ b/src/Application/Reviews/Queries/GetReviews/GetReviewsQuery.cs
@@ -1,8 +1,23 @@
namespace CleanModelContextProtocol.Application.Reviews.Queries.GetReviews;
+using Common.Paging;
using Entities;
using Mediator;
-public class GetReviewsQuery : IRequest>
+///
+/// Lists reviews one page at a time, optionally only those of one movie, by one author, or both.
+///
+public class GetReviewsQuery : IRequest>
{
+ /// Only return reviews of this movie. Leave empty for every movie.
+ public Guid? MovieId { get; init; }
+
+ /// Only return reviews by this author. Leave empty for every author.
+ public Guid? AuthorId { get; init; }
+
+ /// The number of results to skip, 0 for the first page.
+ public int Offset { get; init; }
+
+ /// The largest number of results to return, from 1 to 50.
+ public int Limit { get; init; } = Paging.DefaultLimit;
}
diff --git a/src/Application/Reviews/Queries/GetReviews/GetReviewsValidator.cs b/src/Application/Reviews/Queries/GetReviews/GetReviewsValidator.cs
new file mode 100644
index 0000000..e917878
--- /dev/null
+++ b/src/Application/Reviews/Queries/GetReviews/GetReviewsValidator.cs
@@ -0,0 +1,15 @@
+namespace CleanModelContextProtocol.Application.Reviews.Queries.GetReviews;
+
+using Common.Paging;
+using FluentValidation;
+
+public class GetReviewsValidator : AbstractValidator
+{
+ public GetReviewsValidator()
+ {
+ _ = this.RuleFor(r => r.MovieId).NotEqual(Guid.Empty).WithMessage("A Movie Id can't be empty. Leave it out to list every movie.");
+ _ = this.RuleFor(r => r.AuthorId).NotEqual(Guid.Empty).WithMessage("An Author Id can't be empty. Leave it out to list every author.");
+ _ = this.RuleFor(r => r.Offset).ValidOffset();
+ _ = this.RuleFor(r => r.Limit).ValidLimit();
+ }
+}
diff --git a/src/Application/Reviews/Queries/GetReviewsForAuthors/GetReviewsForAuthorsHandler.cs b/src/Application/Reviews/Queries/GetReviewsForAuthors/GetReviewsForAuthorsHandler.cs
new file mode 100644
index 0000000..4fcf1a9
--- /dev/null
+++ b/src/Application/Reviews/Queries/GetReviewsForAuthors/GetReviewsForAuthorsHandler.cs
@@ -0,0 +1,18 @@
+namespace CleanModelContextProtocol.Application.Reviews.Queries.GetReviewsForAuthors;
+
+using Entities;
+using Mediator;
+
+public class GetReviewsForAuthorsHandler(IReviewsRepository repository) : IRequestHandler>>
+{
+ public async ValueTask>> Handle(GetReviewsForAuthorsQuery request, CancellationToken cancellationToken)
+ {
+ var reviews = (await repository.GetReviewsForAuthors(request.AuthorIds, cancellationToken))
+ .ToLookup(r => r.ReviewAuthor?.Id);
+
+ // Every id gets an entry, so a author with no reviews has an empty list rather than no entry.
+ return request.AuthorIds
+ .Distinct()
+ .ToDictionary(id => id, id => reviews[id].ToList());
+ }
+}
diff --git a/src/Application/Reviews/Queries/GetReviewsForAuthors/GetReviewsForAuthorsQuery.cs b/src/Application/Reviews/Queries/GetReviewsForAuthors/GetReviewsForAuthorsQuery.cs
new file mode 100644
index 0000000..d11cb46
--- /dev/null
+++ b/src/Application/Reviews/Queries/GetReviewsForAuthors/GetReviewsForAuthorsQuery.cs
@@ -0,0 +1,14 @@
+namespace CleanModelContextProtocol.Application.Reviews.Queries.GetReviewsForAuthors;
+
+using Entities;
+using Mediator;
+
+///
+/// Gets every review of several authors in one call, grouped by author. Presentation layers use it to load reviews for a
+/// whole page of authors at once instead of one query per author.
+///
+public class GetReviewsForAuthorsQuery : IRequest>>
+{
+ /// The authors to get the reviews of.
+ public required IReadOnlyCollection AuthorIds { get; init; }
+}
diff --git a/src/Application/Reviews/Queries/GetReviewsForAuthors/GetReviewsForAuthorsValidator.cs b/src/Application/Reviews/Queries/GetReviewsForAuthors/GetReviewsForAuthorsValidator.cs
new file mode 100644
index 0000000..ccad488
--- /dev/null
+++ b/src/Application/Reviews/Queries/GetReviewsForAuthors/GetReviewsForAuthorsValidator.cs
@@ -0,0 +1,15 @@
+namespace CleanModelContextProtocol.Application.Reviews.Queries.GetReviewsForAuthors;
+
+using Common.Paging;
+using FluentValidation;
+
+public class GetReviewsForAuthorsValidator : AbstractValidator
+{
+ public GetReviewsForAuthorsValidator()
+ {
+ _ = this.RuleFor(r => r.AuthorIds)
+ .NotEmpty().WithMessage("At least one Author Id is needed.")
+ .Must(ids => ids.Count <= Paging.MaxLimit).WithMessage($"Reviews can be fetched for at most {Paging.MaxLimit} authors at a time.");
+ _ = this.RuleForEach(r => r.AuthorIds).NotEqual(Guid.Empty).WithMessage("An Author Id can't be empty.");
+ }
+}
diff --git a/src/Application/Reviews/Queries/GetReviewsForMovies/GetReviewsForMoviesHandler.cs b/src/Application/Reviews/Queries/GetReviewsForMovies/GetReviewsForMoviesHandler.cs
new file mode 100644
index 0000000..63fda46
--- /dev/null
+++ b/src/Application/Reviews/Queries/GetReviewsForMovies/GetReviewsForMoviesHandler.cs
@@ -0,0 +1,18 @@
+namespace CleanModelContextProtocol.Application.Reviews.Queries.GetReviewsForMovies;
+
+using Entities;
+using Mediator;
+
+public class GetReviewsForMoviesHandler(IReviewsRepository repository) : IRequestHandler>>
+{
+ public async ValueTask>> Handle(GetReviewsForMoviesQuery request, CancellationToken cancellationToken)
+ {
+ var reviews = (await repository.GetReviewsForMovies(request.MovieIds, cancellationToken))
+ .ToLookup(r => r.ReviewedMovie?.Id);
+
+ // Every id gets an entry, so a movie with no reviews has an empty list rather than no entry.
+ return request.MovieIds
+ .Distinct()
+ .ToDictionary(id => id, id => reviews[id].ToList());
+ }
+}
diff --git a/src/Application/Reviews/Queries/GetReviewsForMovies/GetReviewsForMoviesQuery.cs b/src/Application/Reviews/Queries/GetReviewsForMovies/GetReviewsForMoviesQuery.cs
new file mode 100644
index 0000000..62a0d22
--- /dev/null
+++ b/src/Application/Reviews/Queries/GetReviewsForMovies/GetReviewsForMoviesQuery.cs
@@ -0,0 +1,14 @@
+namespace CleanModelContextProtocol.Application.Reviews.Queries.GetReviewsForMovies;
+
+using Entities;
+using Mediator;
+
+///
+/// Gets every review of several movies in one call, grouped by movie. Presentation layers use it to load reviews for a
+/// whole page of movies at once instead of one query per movie.
+///
+public class GetReviewsForMoviesQuery : IRequest>>
+{
+ /// The movies to get the reviews of.
+ public required IReadOnlyCollection MovieIds { get; init; }
+}
diff --git a/src/Application/Reviews/Queries/GetReviewsForMovies/GetReviewsForMoviesValidator.cs b/src/Application/Reviews/Queries/GetReviewsForMovies/GetReviewsForMoviesValidator.cs
new file mode 100644
index 0000000..f7040a6
--- /dev/null
+++ b/src/Application/Reviews/Queries/GetReviewsForMovies/GetReviewsForMoviesValidator.cs
@@ -0,0 +1,15 @@
+namespace CleanModelContextProtocol.Application.Reviews.Queries.GetReviewsForMovies;
+
+using Common.Paging;
+using FluentValidation;
+
+public class GetReviewsForMoviesValidator : AbstractValidator
+{
+ public GetReviewsForMoviesValidator()
+ {
+ _ = this.RuleFor(r => r.MovieIds)
+ .NotEmpty().WithMessage("At least one Movie Id is needed.")
+ .Must(ids => ids.Count <= Paging.MaxLimit).WithMessage($"Reviews can be fetched for at most {Paging.MaxLimit} movies at a time.");
+ _ = this.RuleForEach(r => r.MovieIds).NotEqual(Guid.Empty).WithMessage("A Movie Id can't be empty.");
+ }
+}
diff --git a/src/Application/Reviews/Queries/SearchReviews/SearchReviewsHandler.cs b/src/Application/Reviews/Queries/SearchReviews/SearchReviewsHandler.cs
deleted file mode 100644
index df733e3..0000000
--- a/src/Application/Reviews/Queries/SearchReviews/SearchReviewsHandler.cs
+++ /dev/null
@@ -1,19 +0,0 @@
-namespace CleanModelContextProtocol.Application.Reviews.Queries.SearchReviews;
-
-using System.Threading;
-using System.Threading.Tasks;
-using Common.Paging;
-using Entities;
-using Mediator;
-
-public class SearchReviewsHandler(IReviewsRepository repository) : IRequestHandler>
-{
- public async ValueTask> Handle(SearchReviewsQuery request, CancellationToken cancellationToken)
- {
- _ = Paging.TryDecode(request.Cursor, out var offset);
-
- var (items, totalCount) = await repository.SearchReviews(request.MovieId, request.AuthorId, offset, request.Limit, cancellationToken);
-
- return Paging.ToPage(items, totalCount, offset);
- }
-}
diff --git a/src/Application/Reviews/Queries/SearchReviews/SearchReviewsQuery.cs b/src/Application/Reviews/Queries/SearchReviews/SearchReviewsQuery.cs
deleted file mode 100644
index 2080520..0000000
--- a/src/Application/Reviews/Queries/SearchReviews/SearchReviewsQuery.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-namespace CleanModelContextProtocol.Application.Reviews.Queries.SearchReviews;
-
-using Common.Paging;
-using Entities;
-using Mediator;
-
-///
-/// Finds reviews, optionally only those for one movie or by one author, one page at a time.
-///
-public class SearchReviewsQuery : IRequest>
-{
- /// Only return reviews of this movie. Leave empty for every movie.
- public Guid? MovieId { get; init; }
-
- /// Only return reviews by this author. Leave empty for every author.
- public Guid? AuthorId { get; init; }
-
- /// The largest number of results to return, from 1 to 50.
- public int Limit { get; init; } = Paging.DefaultLimit;
-
- /// The cursor from a previous page, or empty for the first page.
- public string Cursor { get; init; }
-}
diff --git a/src/Application/Reviews/Queries/SearchReviews/SearchReviewsValidator.cs b/src/Application/Reviews/Queries/SearchReviews/SearchReviewsValidator.cs
deleted file mode 100644
index f37375b..0000000
--- a/src/Application/Reviews/Queries/SearchReviews/SearchReviewsValidator.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-namespace CleanModelContextProtocol.Application.Reviews.Queries.SearchReviews;
-
-using Common.Paging;
-using FluentValidation;
-
-public class SearchReviewsValidator : AbstractValidator
-{
- public SearchReviewsValidator()
- {
- _ = this.RuleFor(r => r.MovieId).NotEqual(Guid.Empty).WithMessage("A Movie Id can't be empty. Leave it out to search every movie.");
- _ = this.RuleFor(r => r.AuthorId).NotEqual(Guid.Empty).WithMessage("An Author Id can't be empty. Leave it out to search every author.");
- _ = this.RuleFor(r => r.Limit).ValidLimit();
- _ = this.RuleFor(r => r.Cursor).ValidCursor();
- }
-}
diff --git a/src/Application/Versions/Entities/Version.cs b/src/Application/Versions/Entities/Version.cs
index 1c064ee..9eaf65d 100644
--- a/src/Application/Versions/Entities/Version.cs
+++ b/src/Application/Versions/Entities/Version.cs
@@ -9,11 +9,11 @@ public class Version
/// The assembly file version.
///
/// 1.1.0.0
- public string FileVersion { get; init; }
+ public required string FileVersion { get; init; }
///
/// The informational version, which can include a pre-release label or commit hash.
///
/// 1.1.0+e30eba8
- public string InformationalVersion { get; init; }
+ public required string InformationalVersion { get; init; }
}
diff --git a/src/Infrastructure/Databases/MovieReviews/Configuration/EntityConfiguration.cs b/src/Infrastructure/Databases/MovieReviews/Configuration/EntityConfiguration.cs
index bf6ec2a..fb4ce72 100644
--- a/src/Infrastructure/Databases/MovieReviews/Configuration/EntityConfiguration.cs
+++ b/src/Infrastructure/Databases/MovieReviews/Configuration/EntityConfiguration.cs
@@ -11,7 +11,7 @@ public virtual void Configure(EntityTypeBuilder builder)
{
_ = builder.HasKey(e => e.Id);
_ = builder.Property(m => m.Id).ValueGeneratedOnAdd().IsRequired();
- _ = builder.Property(m => m.DateCreated).ValueGeneratedOnAdd().IsRequired();
- _ = builder.Property(m => m.DateModified).ValueGeneratedOnAdd().IsRequired();
+ _ = builder.Property(m => m.DateCreated).IsRequired();
+ _ = builder.Property(m => m.DateModified).IsRequired();
}
}
diff --git a/src/Infrastructure/Databases/MovieReviews/EntityFrameworkMovieReviewsRepository.cs b/src/Infrastructure/Databases/MovieReviews/EntityFrameworkMovieReviewsRepository.cs
index 8dc950b..3c15542 100644
--- a/src/Infrastructure/Databases/MovieReviews/EntityFrameworkMovieReviewsRepository.cs
+++ b/src/Infrastructure/Databases/MovieReviews/EntityFrameworkMovieReviewsRepository.cs
@@ -2,16 +2,15 @@ namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews;
using System;
using Application.Authors;
-using Application.Common.Enums;
-using Application.Common.Exceptions;
using Application.Movies;
using Application.Reviews;
-using Extensions;
using Mapping;
using Microsoft.EntityFrameworkCore;
using Models;
using ApplicationAuthor = Application.Authors.Entities.Author;
+using ApplicationAuthorSummary = Application.Authors.Entities.AuthorSummary;
using ApplicationMovie = Application.Movies.Entities.Movie;
+using ApplicationMovieSummary = Application.Movies.Entities.MovieSummary;
using ApplicationReview = Application.Reviews.Entities.Review;
internal class EntityFrameworkMovieReviewsRepository : IAuthorsRepository, IMoviesRepository, IReviewsRepository
@@ -32,43 +31,12 @@ public EntityFrameworkMovieReviewsRepository(
this.context = context;
this.timeProvider = timeProvider;
this.mapper = mapper;
-
- _ = this.context.Database.EnsureDeleted();
- _ = this.context.Database.EnsureCreated();
- _ = this.context.AddData();
}
#region Authors
- public virtual async Task> GetAuthors(CancellationToken cancellationToken)
- {
- var authors = await this.context.Authors
- .Include(a => a.Reviews)
- .ThenInclude(r => r.ReviewedMovie)
- .AsNoTracking()
- .ToListAsync(cancellationToken);
-
- return [.. authors.Select(this.mapper.ToDomain)];
- }
-
- public virtual async Task GetAuthorById(Guid id, CancellationToken cancellationToken)
- {
- var author = await this.context.Authors
- .Where(r => r.Id == id).Include(a => a.Reviews)
- .ThenInclude(r => r.ReviewedMovie)
- .AsNoTracking()
- .FirstOrDefaultAsync(cancellationToken);
-
- return this.mapper.ToDomain(author);
- }
-
- public virtual async Task AuthorExists(Guid id, CancellationToken cancellationToken)
- {
- return await this.context.Authors.AsNoTracking().AnyAsync(a => a.Id == id, cancellationToken);
- }
-
- public virtual async Task<(List Items, int TotalCount)> SearchAuthors(
- string query,
+ public virtual async Task<(List Items, int TotalCount)> GetAuthors(
+ string? query,
int offset,
int limit,
CancellationToken cancellationToken)
@@ -77,60 +45,55 @@ public virtual async Task AuthorExists(Guid id, CancellationToken cancella
if (!string.IsNullOrWhiteSpace(query))
{
- var term = query.Trim();
+ var pattern = ContainsPattern(query);
- authors = authors.Where(a => (a.FirstName + " " + a.LastName).Contains(term, StringComparison.OrdinalIgnoreCase));
+ authors = authors.Where(a => EF.Functions.Like(a.FirstName + " " + a.LastName, pattern, EscapeCharacter));
}
var totalCount = await authors.CountAsync(cancellationToken);
+ // The review count and average are worked out by the database, so the reviews themselves are never loaded.
var result = await authors
.OrderBy(a => a.LastName)
.ThenBy(a => a.FirstName)
.ThenBy(a => a.Id)
.Skip(offset)
.Take(limit)
- .Include(a => a.Reviews)
- .ThenInclude(r => r.ReviewedMovie)
+ .Select(a => new
+ {
+ a.Id,
+ a.FirstName,
+ a.LastName,
+ ReviewCount = a.Reviews.Count,
+ AverageStars = a.Reviews.Average(r => (double?)r.Stars)
+ })
.ToListAsync(cancellationToken);
- return ([.. result.Select(this.mapper.ToDomain)], totalCount);
+ return ([.. result.Select(a => new ApplicationAuthorSummary(a.Id, a.FirstName, a.LastName, a.ReviewCount, RoundStars(a.AverageStars)))], totalCount);
}
- #endregion Authors
-
- #region Movies
-
- public virtual async Task> GetMovies(CancellationToken cancellationToken)
+ public virtual async Task GetAuthorById(Guid id, CancellationToken cancellationToken)
{
- var result = await this.context.Movies
- .Include(m => m.Reviews)
- .ThenInclude(r => r.ReviewAuthor)
- .AsNoTracking()
- .ToListAsync(cancellationToken);
-
- return [.. result.Select(this.mapper.ToDomain)];
- }
-
- public virtual async Task GetMovieById(Guid id, CancellationToken cancellationToken)
- {
- var result = await this.context.Movies
- .Where(r => r.Id == id)
- .Include(m => m.Reviews)
- .ThenInclude(r => r.ReviewAuthor)
+ var author = await this.context.Authors
+ .Where(r => r.Id == id).Include(a => a.Reviews)
+ .ThenInclude(r => r.ReviewedMovie)
.AsNoTracking()
.FirstOrDefaultAsync(cancellationToken);
- return this.mapper.ToDomain(result);
+ return author is null ? null : this.mapper.ToDomain(author);
}
- public virtual async Task MovieExists(Guid id, CancellationToken cancellationToken)
+ public virtual async Task AuthorExists(Guid id, CancellationToken cancellationToken)
{
- return await this.context.Movies.AsNoTracking().AnyAsync(m => m.Id == id, cancellationToken);
+ return await this.context.Authors.AsNoTracking().AnyAsync(a => a.Id == id, cancellationToken);
}
- public virtual async Task<(List Items, int TotalCount)> SearchMovies(
- string query,
+ #endregion Authors
+
+ #region Movies
+
+ public virtual async Task<(List Items, int TotalCount)> GetMovies(
+ string? query,
int offset,
int limit,
CancellationToken cancellationToken)
@@ -139,23 +102,46 @@ public virtual async Task MovieExists(Guid id, CancellationToken cancellat
if (!string.IsNullOrWhiteSpace(query))
{
- var term = query.Trim();
+ var pattern = ContainsPattern(query);
- movies = movies.Where(m => m.Title.Contains(term, StringComparison.OrdinalIgnoreCase));
+ movies = movies.Where(m => EF.Functions.Like(m.Title, pattern, EscapeCharacter));
}
var totalCount = await movies.CountAsync(cancellationToken);
+ // The review count and average are worked out by the database, so the reviews themselves are never loaded.
var result = await movies
.OrderBy(m => m.Title)
.ThenBy(m => m.Id)
.Skip(offset)
.Take(limit)
+ .Select(m => new
+ {
+ m.Id,
+ m.Title,
+ ReviewCount = m.Reviews.Count,
+ AverageStars = m.Reviews.Average(r => (double?)r.Stars)
+ })
+ .ToListAsync(cancellationToken);
+
+ return ([.. result.Select(m => new ApplicationMovieSummary(m.Id, m.Title, m.ReviewCount, RoundStars(m.AverageStars)))], totalCount);
+ }
+
+ public virtual async Task GetMovieById(Guid id, CancellationToken cancellationToken)
+ {
+ var result = await this.context.Movies
+ .Where(r => r.Id == id)
.Include(m => m.Reviews)
.ThenInclude(r => r.ReviewAuthor)
- .ToListAsync(cancellationToken);
+ .AsNoTracking()
+ .FirstOrDefaultAsync(cancellationToken);
- return ([.. result.Select(this.mapper.ToDomain)], totalCount);
+ return result is null ? null : this.mapper.ToDomain(result);
+ }
+
+ public virtual async Task MovieExists(Guid id, CancellationToken cancellationToken)
+ {
+ return await this.context.Movies.AsNoTracking().AnyAsync(m => m.Id == id, cancellationToken);
}
#endregion Movies
@@ -168,13 +154,15 @@ public async Task CreateReview(
int stars,
CancellationToken cancellationToken)
{
+ var now = this.timeProvider.GetUtcNow().UtcDateTime;
+
var review = new Review
{
ReviewAuthorId = authorId,
ReviewedMovieId = movieId,
Stars = stars,
- DateCreated = this.timeProvider.GetUtcNow().UtcDateTime,
- DateModified = this.timeProvider.GetUtcNow().UtcDateTime
+ DateCreated = now,
+ DateModified = now
};
var id = this.context.Add(review).Entity.Id;
@@ -193,31 +181,77 @@ public async Task CreateReview(
public async Task DeleteReview(Guid id, CancellationToken cancellationToken)
{
- try
+ var deleted = await this.context.Reviews
+ .Where(r => r.Id == id)
+ .ExecuteDeleteAsync(cancellationToken);
+
+ return deleted > 0;
+ }
+
+ public async Task<(List Items, int TotalCount)> GetReviews(
+ Guid? movieId,
+ Guid? authorId,
+ int offset,
+ int limit,
+ CancellationToken cancellationToken)
+ {
+ var reviews = this.context.Reviews.AsNoTracking();
+
+ if (movieId is Guid reviewedMovieId)
{
- _ = this.context.Remove(this.context.Reviews.Single(r => r.Id == id));
- _ = await this.context.SaveChangesAsync(cancellationToken);
+ reviews = reviews.Where(r => r.ReviewedMovieId == reviewedMovieId);
}
- catch (Exception)
+
+ if (authorId is Guid reviewAuthorId)
{
- return false;
+ reviews = reviews.Where(r => r.ReviewAuthorId == reviewAuthorId);
}
- return true;
+ var totalCount = await reviews.CountAsync(cancellationToken);
+
+ var result = await reviews
+ .Include(r => r.ReviewAuthor)
+ .Include(r => r.ReviewedMovie)
+ .OrderBy(r => r.ReviewedMovie.Title)
+ .ThenBy(r => r.ReviewAuthor.LastName)
+ .ThenBy(r => r.Id)
+ .Skip(offset)
+ .Take(limit)
+ .ToListAsync(cancellationToken);
+
+ return ([.. result.Select(this.mapper.ToDomain)], totalCount);
}
- public async Task> GetReviews(CancellationToken cancellationToken)
+ public async Task> GetReviewsForMovies(IReadOnlyCollection movieIds, CancellationToken cancellationToken)
{
var result = await this.context.Reviews
+ .AsNoTracking()
+ .Where(r => movieIds.Contains(r.ReviewedMovieId))
.Include(r => r.ReviewAuthor)
.Include(r => r.ReviewedMovie)
+ .OrderBy(r => r.ReviewAuthor.LastName)
+ .ThenBy(r => r.ReviewAuthor.FirstName)
+ .ThenBy(r => r.Id)
+ .ToListAsync(cancellationToken);
+
+ return [.. result.Select(this.mapper.ToDomain)];
+ }
+
+ public async Task> GetReviewsForAuthors(IReadOnlyCollection authorIds, CancellationToken cancellationToken)
+ {
+ var result = await this.context.Reviews
.AsNoTracking()
+ .Where(r => authorIds.Contains(r.ReviewAuthorId))
+ .Include(r => r.ReviewAuthor)
+ .Include(r => r.ReviewedMovie)
+ .OrderBy(r => r.ReviewedMovie.Title)
+ .ThenBy(r => r.Id)
.ToListAsync(cancellationToken);
return [.. result.Select(this.mapper.ToDomain)];
}
- public async Task GetReviewById(Guid id, CancellationToken cancellationToken)
+ public async Task GetReviewById(Guid id, CancellationToken cancellationToken)
{
var result = await this.context.Reviews
.Where(r => r.Id == id)
@@ -226,7 +260,7 @@ public async Task GetReviewById(Guid id, CancellationToken ca
.AsNoTracking()
.FirstOrDefaultAsync(cancellationToken);
- return this.mapper.ToDomain(result);
+ return result is null ? null : this.mapper.ToDomain(result);
}
public async Task ReviewExists(Guid id, CancellationToken cancellationToken)
@@ -234,68 +268,49 @@ public async Task ReviewExists(Guid id, CancellationToken cancellationToke
return await this.context.Reviews.AnyAsync(r => r.Id == id, cancellationToken);
}
- public async Task<(List Items, int TotalCount)> SearchReviews(
- Guid? movieId,
- Guid? authorId,
- int offset,
- int limit,
- CancellationToken cancellationToken)
+ public async Task UpdateReview(Guid id, int stars, CancellationToken cancellationToken)
{
- var reviews = this.context.Reviews.AsNoTracking();
+ var now = this.timeProvider.GetUtcNow().UtcDateTime;
- if (movieId is Guid reviewedMovieId)
- {
- reviews = reviews.Where(r => r.ReviewedMovieId == reviewedMovieId);
- }
+ var updated = await this.context.Reviews
+ .Where(r => r.Id == id)
+ .ExecuteUpdateAsync(
+ setters => setters
+ .SetProperty(r => r.Stars, stars)
+ .SetProperty(r => r.DateModified, now),
+ cancellationToken);
- if (authorId is Guid reviewAuthorId)
- {
- reviews = reviews.Where(r => r.ReviewAuthorId == reviewAuthorId);
- }
+ return updated > 0;
+ }
- var totalCount = await reviews.CountAsync(cancellationToken);
+ #endregion Reviews
- var result = await reviews
- .Include(r => r.ReviewAuthor)
- .Include(r => r.ReviewedMovie)
- .OrderBy(r => r.ReviewedMovie.Title)
- .ThenBy(r => r.ReviewAuthor.LastName)
- .ThenBy(r => r.Id)
- .Skip(offset)
- .Take(limit)
- .ToListAsync(cancellationToken);
+ #region Helpers
- return ([.. result.Select(this.mapper.ToDomain)], totalCount);
+ private static double? RoundStars(double? averageStars)
+ {
+ return averageStars is null ? null : Math.Round(averageStars.Value, 1, MidpointRounding.AwayFromZero);
}
- public async Task UpdateReview(
- Guid id,
- Guid authorId,
- Guid movieId,
- int stars,
- CancellationToken cancellationToken)
- {
- try
- {
- var review = this.context.Reviews.FirstOrDefault(r => r.Id == id);
+ #endregion Helpers
- NotFoundException.ThrowIfNull(review, EntityType.Review);
+ #region Search
- review.Stars = stars;
- review.ReviewAuthorId = authorId;
- review.ReviewedMovieId = movieId;
- review.DateModified = this.timeProvider.GetUtcNow().UtcDateTime;
+ private const string EscapeCharacter = "\\";
- _ = this.context.Update(review);
- _ = await this.context.SaveChangesAsync(cancellationToken);
- }
- catch (Exception)
- {
- return false;
- }
+ ///
+ /// Builds a LIKE pattern that matches any text containing the search term. LIKE ignores case for
+ /// ASCII text in SQLite and SQL Server, and the term's own wildcards are escaped so they match literally.
+ ///
+ private static string ContainsPattern(string query)
+ {
+ var term = query.Trim()
+ .Replace(EscapeCharacter, EscapeCharacter + EscapeCharacter, StringComparison.Ordinal)
+ .Replace("%", EscapeCharacter + "%", StringComparison.Ordinal)
+ .Replace("_", EscapeCharacter + "_", StringComparison.Ordinal);
- return true;
+ return $"%{term}%";
}
- #endregion Reviews
+ #endregion Search
}
diff --git a/src/Infrastructure/Databases/MovieReviews/Extensions/MovieReviewsDbContextExtensions.cs b/src/Infrastructure/Databases/MovieReviews/Extensions/MovieReviewsDbContextExtensions.cs
index f1333df..6aef8c3 100644
--- a/src/Infrastructure/Databases/MovieReviews/Extensions/MovieReviewsDbContextExtensions.cs
+++ b/src/Infrastructure/Databases/MovieReviews/Extensions/MovieReviewsDbContextExtensions.cs
@@ -6,34 +6,46 @@ namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Extens
internal static class MovieReviewsDbContextExtensions
{
+ // A fixed seed and reference date give the same sample data on every run.
+ private const int Seed = 20211014;
+ private static readonly DateTime ReferenceDate = new(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc);
+
public static MovieReviewsDbContext AddData(this MovieReviewsDbContext context)
{
+ if (context.Authors.Any())
+ {
+ return context;
+ }
+
var authors = new Faker()
- .RuleFor(a => a.Id, _ => Guid.NewGuid())
+ .UseSeed(Seed)
+ .RuleFor(a => a.Id, f => f.Random.Guid())
.RuleFor(a => a.FirstName, f => f.Person.FirstName)
.RuleFor(a => a.LastName, f => f.Person.LastName)
- .RuleFor(a => a.DateCreated, f => f.Date.Past())
- .RuleFor(a => a.DateModified, f => f.Date.Past())
+ .RuleFor(a => a.DateCreated, f => f.Date.Past(refDate: ReferenceDate))
+ .RuleFor(a => a.DateModified, f => f.Date.Past(refDate: ReferenceDate))
.Generate(15);
context.AddRange(authors);
var movies = new Faker()
- .RuleFor(m => m.Id, _ => Guid.NewGuid())
+ .UseSeed(Seed)
+ .RuleFor(m => m.Id, f => f.Random.Guid())
.RuleFor(m => m.Title, f => f.Company.CatchPhrase())
- .RuleFor(m => m.DateCreated, f => f.Date.Past())
- .RuleFor(m => m.DateModified, f => f.Date.Past())
+ .RuleFor(m => m.DateCreated, f => f.Date.Past(refDate: ReferenceDate))
+ .RuleFor(m => m.DateModified, f => f.Date.Past(refDate: ReferenceDate))
.Generate(50);
context.AddRange(movies);
var reviews = new Faker()
- .RuleFor(r => r.Id, _ => Guid.NewGuid())
+ .UseSeed(Seed)
+ .RuleFor(r => r.Id, f => f.Random.Guid())
.RuleFor(r => r.ReviewedMovieId, f => f.PickRandom(movies).Id)
.RuleFor(r => r.ReviewAuthorId, f => f.PickRandom(authors).Id)
.RuleFor(r => r.Stars, f => f.Random.Number(1, 5))
- .RuleFor(r => r.DateCreated, f => f.Date.Past())
- .RuleFor(r => r.DateModified, f => f.Date.Past())
+ .RuleFor(r => r.DateCreated, f => f.Date.Past(refDate: ReferenceDate))
+ .RuleFor(r => r.DateModified, f => f.Date.Past(refDate: ReferenceDate))
.Generate(150);
context.AddRange(reviews);
diff --git a/src/Infrastructure/Databases/MovieReviews/Mapping/MovieReviewsMapper.cs b/src/Infrastructure/Databases/MovieReviews/Mapping/MovieReviewsMapper.cs
index f5dfcd2..da1f566 100644
--- a/src/Infrastructure/Databases/MovieReviews/Mapping/MovieReviewsMapper.cs
+++ b/src/Infrastructure/Databases/MovieReviews/Mapping/MovieReviewsMapper.cs
@@ -2,10 +2,10 @@ namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Mappin
using Riok.Mapperly.Abstractions;
using AppAuthor = Application.Authors.Entities.Author;
-using AppReviewAuthor = Application.Authors.Entities.ReviewAuthor;
using AppMovie = Application.Movies.Entities.Movie;
-using AppReviewedMovie = Application.Movies.Entities.ReviewedMovie;
using AppReview = Application.Reviews.Entities.Review;
+using AppReviewAuthor = Application.Authors.Entities.ReviewAuthor;
+using AppReviewedMovie = Application.Movies.Entities.ReviewedMovie;
using InfraAuthor = Models.Author;
using InfraMovie = Models.Movie;
using InfraReview = Models.Review;
@@ -15,6 +15,8 @@ internal partial class MovieReviewsMapper
{
// Infrastructure → Domain
+ [MapperIgnoreSource(nameof(InfraAuthor.DateCreated))]
+ [MapperIgnoreSource(nameof(InfraAuthor.DateModified))]
public partial AppAuthor ToDomain(InfraAuthor author);
[MapperIgnoreSource(nameof(InfraAuthor.Reviews))]
@@ -22,6 +24,8 @@ internal partial class MovieReviewsMapper
[MapperIgnoreSource(nameof(InfraAuthor.DateModified))]
public partial AppReviewAuthor ToReviewAuthor(InfraAuthor author);
+ [MapperIgnoreSource(nameof(InfraMovie.DateCreated))]
+ [MapperIgnoreSource(nameof(InfraMovie.DateModified))]
public partial AppMovie ToDomain(InfraMovie movie);
[MapperIgnoreSource(nameof(InfraMovie.Reviews))]
diff --git a/src/Infrastructure/Databases/MovieReviews/Migrations/20261028000000_InitialCreate.Designer.cs b/src/Infrastructure/Databases/MovieReviews/Migrations/20261028000000_InitialCreate.Designer.cs
new file mode 100644
index 0000000..daa9732
--- /dev/null
+++ b/src/Infrastructure/Databases/MovieReviews/Migrations/20261028000000_InitialCreate.Designer.cs
@@ -0,0 +1,130 @@
+//
+using System;
+using CleanModelContextProtocol.Infrastructure.Databases.MovieReviews;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+#nullable disable
+
+namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Migrations
+{
+ [DbContext(typeof(MovieReviewsDbContext))]
+ [Migration("20261028000000_InitialCreate")]
+ partial class InitialCreate
+ {
+ ///
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder.HasAnnotation("ProductVersion", "10.0.14");
+
+ modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Author", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("DateCreated")
+ .HasColumnType("TEXT");
+
+ b.Property("DateModified")
+ .HasColumnType("TEXT");
+
+ b.Property("FirstName")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property("LastName")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("Authors");
+ });
+
+ modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Movie", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("DateCreated")
+ .HasColumnType("TEXT");
+
+ b.Property("DateModified")
+ .HasColumnType("TEXT");
+
+ b.Property("Title")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("Movies");
+ });
+
+ modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Review", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("DateCreated")
+ .HasColumnType("TEXT");
+
+ b.Property("DateModified")
+ .HasColumnType("TEXT");
+
+ b.Property("ReviewAuthorId")
+ .HasColumnType("TEXT");
+
+ b.Property("ReviewedMovieId")
+ .HasColumnType("TEXT");
+
+ b.Property("Stars")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("ReviewAuthorId");
+
+ b.HasIndex("ReviewedMovieId");
+
+ b.ToTable("Reviews");
+ });
+
+ modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Review", b =>
+ {
+ b.HasOne("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Author", "ReviewAuthor")
+ .WithMany("Reviews")
+ .HasForeignKey("ReviewAuthorId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Movie", "ReviewedMovie")
+ .WithMany("Reviews")
+ .HasForeignKey("ReviewedMovieId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("ReviewAuthor");
+
+ b.Navigation("ReviewedMovie");
+ });
+
+ modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Author", b =>
+ {
+ b.Navigation("Reviews");
+ });
+
+ modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Movie", b =>
+ {
+ b.Navigation("Reviews");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/src/Infrastructure/Databases/MovieReviews/Migrations/20261028000000_InitialCreate.cs b/src/Infrastructure/Databases/MovieReviews/Migrations/20261028000000_InitialCreate.cs
new file mode 100644
index 0000000..3356e0d
--- /dev/null
+++ b/src/Infrastructure/Databases/MovieReviews/Migrations/20261028000000_InitialCreate.cs
@@ -0,0 +1,96 @@
+//
+using System;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Migrations
+{
+ ///
+ public partial class InitialCreate : Migration
+ {
+ ///
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.CreateTable(
+ name: "Authors",
+ columns: table => new
+ {
+ Id = table.Column(type: "TEXT", nullable: false),
+ FirstName = table.Column(type: "TEXT", nullable: false),
+ LastName = table.Column(type: "TEXT", nullable: false),
+ DateCreated = table.Column(type: "TEXT", nullable: false),
+ DateModified = table.Column(type: "TEXT", nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_Authors", x => x.Id);
+ });
+
+ migrationBuilder.CreateTable(
+ name: "Movies",
+ columns: table => new
+ {
+ Id = table.Column(type: "TEXT", nullable: false),
+ Title = table.Column(type: "TEXT", nullable: false),
+ DateCreated = table.Column(type: "TEXT", nullable: false),
+ DateModified = table.Column(type: "TEXT", nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_Movies", x => x.Id);
+ });
+
+ migrationBuilder.CreateTable(
+ name: "Reviews",
+ columns: table => new
+ {
+ Id = table.Column(type: "TEXT", nullable: false),
+ Stars = table.Column(type: "INTEGER", nullable: false),
+ ReviewedMovieId = table.Column(type: "TEXT", nullable: false),
+ ReviewAuthorId = table.Column(type: "TEXT", nullable: false),
+ DateCreated = table.Column(type: "TEXT", nullable: false),
+ DateModified = table.Column(type: "TEXT", nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_Reviews", x => x.Id);
+ table.ForeignKey(
+ name: "FK_Reviews_Authors_ReviewAuthorId",
+ column: x => x.ReviewAuthorId,
+ principalTable: "Authors",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Cascade);
+ table.ForeignKey(
+ name: "FK_Reviews_Movies_ReviewedMovieId",
+ column: x => x.ReviewedMovieId,
+ principalTable: "Movies",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Cascade);
+ });
+
+ migrationBuilder.CreateIndex(
+ name: "IX_Reviews_ReviewAuthorId",
+ table: "Reviews",
+ column: "ReviewAuthorId");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_Reviews_ReviewedMovieId",
+ table: "Reviews",
+ column: "ReviewedMovieId");
+ }
+
+ ///
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropTable(
+ name: "Reviews");
+
+ migrationBuilder.DropTable(
+ name: "Authors");
+
+ migrationBuilder.DropTable(
+ name: "Movies");
+ }
+ }
+}
diff --git a/src/Infrastructure/Databases/MovieReviews/Migrations/MovieReviewsDbContextModelSnapshot.cs b/src/Infrastructure/Databases/MovieReviews/Migrations/MovieReviewsDbContextModelSnapshot.cs
new file mode 100644
index 0000000..3552e71
--- /dev/null
+++ b/src/Infrastructure/Databases/MovieReviews/Migrations/MovieReviewsDbContextModelSnapshot.cs
@@ -0,0 +1,127 @@
+//
+using System;
+using CleanModelContextProtocol.Infrastructure.Databases.MovieReviews;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+#nullable disable
+
+namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Migrations
+{
+ [DbContext(typeof(MovieReviewsDbContext))]
+ partial class MovieReviewsDbContextModelSnapshot : ModelSnapshot
+ {
+ protected override void BuildModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder.HasAnnotation("ProductVersion", "10.0.14");
+
+ modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Author", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("DateCreated")
+ .HasColumnType("TEXT");
+
+ b.Property("DateModified")
+ .HasColumnType("TEXT");
+
+ b.Property("FirstName")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property("LastName")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("Authors");
+ });
+
+ modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Movie", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("DateCreated")
+ .HasColumnType("TEXT");
+
+ b.Property("DateModified")
+ .HasColumnType("TEXT");
+
+ b.Property("Title")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("Movies");
+ });
+
+ modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Review", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("DateCreated")
+ .HasColumnType("TEXT");
+
+ b.Property("DateModified")
+ .HasColumnType("TEXT");
+
+ b.Property("ReviewAuthorId")
+ .HasColumnType("TEXT");
+
+ b.Property("ReviewedMovieId")
+ .HasColumnType("TEXT");
+
+ b.Property("Stars")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("ReviewAuthorId");
+
+ b.HasIndex("ReviewedMovieId");
+
+ b.ToTable("Reviews");
+ });
+
+ modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Review", b =>
+ {
+ b.HasOne("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Author", "ReviewAuthor")
+ .WithMany("Reviews")
+ .HasForeignKey("ReviewAuthorId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Movie", "ReviewedMovie")
+ .WithMany("Reviews")
+ .HasForeignKey("ReviewedMovieId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("ReviewAuthor");
+
+ b.Navigation("ReviewedMovie");
+ });
+
+ modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Author", b =>
+ {
+ b.Navigation("Reviews");
+ });
+
+ modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Movie", b =>
+ {
+ b.Navigation("Reviews");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/src/Infrastructure/Databases/MovieReviews/Models/Author.cs b/src/Infrastructure/Databases/MovieReviews/Models/Author.cs
index f1dda04..8d8ef9d 100644
--- a/src/Infrastructure/Databases/MovieReviews/Models/Author.cs
+++ b/src/Infrastructure/Databases/MovieReviews/Models/Author.cs
@@ -5,9 +5,9 @@ namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models
[ExcludeFromCodeCoverage]
internal record Author : Entity
{
- public string FirstName { get; init; }
+ public required string FirstName { get; init; }
- public string LastName { get; init; }
+ public required string LastName { get; init; }
- public ICollection Reviews { get; init; }
+ public ICollection Reviews { get; init; } = [];
}
diff --git a/src/Infrastructure/Databases/MovieReviews/Models/Movie.cs b/src/Infrastructure/Databases/MovieReviews/Models/Movie.cs
index fdd298c..0daf229 100644
--- a/src/Infrastructure/Databases/MovieReviews/Models/Movie.cs
+++ b/src/Infrastructure/Databases/MovieReviews/Models/Movie.cs
@@ -5,7 +5,7 @@ namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models
[ExcludeFromCodeCoverage]
internal record Movie : Entity
{
- public string Title { get; init; }
+ public required string Title { get; init; }
- public ICollection Reviews { get; init; }
+ public ICollection Reviews { get; init; } = [];
}
diff --git a/src/Infrastructure/Databases/MovieReviews/Models/Review.cs b/src/Infrastructure/Databases/MovieReviews/Models/Review.cs
index 6e415a5..9aa944f 100644
--- a/src/Infrastructure/Databases/MovieReviews/Models/Review.cs
+++ b/src/Infrastructure/Databases/MovieReviews/Models/Review.cs
@@ -11,10 +11,10 @@ internal record Review : Entity
[ForeignKey("ReviewedMovie")]
public Guid ReviewedMovieId { get; set; }
- public Movie ReviewedMovie { get; init; }
+ public Movie ReviewedMovie { get; init; } = null!;
[ForeignKey("ReviewAuthor")]
public Guid ReviewAuthorId { get; set; }
- public Author ReviewAuthor { get; init; }
+ public Author ReviewAuthor { get; init; } = null!;
}
diff --git a/src/Infrastructure/Databases/MovieReviews/MovieReviewsDatabase.cs b/src/Infrastructure/Databases/MovieReviews/MovieReviewsDatabase.cs
new file mode 100644
index 0000000..14f6ba4
--- /dev/null
+++ b/src/Infrastructure/Databases/MovieReviews/MovieReviewsDatabase.cs
@@ -0,0 +1,34 @@
+namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews;
+
+using Microsoft.Data.Sqlite;
+
+///
+/// The connection details of the movie reviews database.
+///
+///
+/// A shared in-memory SQLite database, such as Data Source=Movies;Mode=Memory;Cache=Shared, only lives while a
+/// connection to it is open, so this keeps one open for as long as the application runs.
+///
+internal sealed class MovieReviewsDatabase(string connectionString) : IDisposable
+{
+ private SqliteConnection? keepAlive;
+
+ public string ConnectionString { get; } = connectionString;
+
+ public bool IsInMemory => new SqliteConnectionStringBuilder(this.ConnectionString).Mode == SqliteOpenMode.Memory;
+
+ public void KeepAlive()
+ {
+ if (this.IsInMemory && this.keepAlive is null)
+ {
+ this.keepAlive = new SqliteConnection(this.ConnectionString);
+ this.keepAlive.Open();
+ }
+ }
+
+ public void Dispose()
+ {
+ this.keepAlive?.Dispose();
+ this.keepAlive = null;
+ }
+}
diff --git a/src/Infrastructure/Databases/MovieReviews/MovieReviewsDbContext.cs b/src/Infrastructure/Databases/MovieReviews/MovieReviewsDbContext.cs
index 4e2d69c..24cce2e 100644
--- a/src/Infrastructure/Databases/MovieReviews/MovieReviewsDbContext.cs
+++ b/src/Infrastructure/Databases/MovieReviews/MovieReviewsDbContext.cs
@@ -6,9 +6,9 @@ namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews;
internal class MovieReviewsDbContext(DbContextOptions options) : DbContext(options)
{
- public DbSet Authors { get; set; }
- public DbSet Movies { get; set; }
- public DbSet Reviews { get; set; }
+ public DbSet Authors => this.Set();
+ public DbSet Movies => this.Set();
+ public DbSet Reviews => this.Set();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
diff --git a/src/Infrastructure/Databases/MovieReviews/MovieReviewsDbContextFactory.cs b/src/Infrastructure/Databases/MovieReviews/MovieReviewsDbContextFactory.cs
new file mode 100644
index 0000000..c8a8f47
--- /dev/null
+++ b/src/Infrastructure/Databases/MovieReviews/MovieReviewsDbContextFactory.cs
@@ -0,0 +1,22 @@
+namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews;
+
+using System.Diagnostics.CodeAnalysis;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Design;
+
+///
+/// Lets the EF Core tools create the context, for example to add a migration:
+/// dotnet ef migrations add Name --project src/Infrastructure --output-dir Databases/MovieReviews/Migrations.
+///
+[ExcludeFromCodeCoverage]
+internal class MovieReviewsDbContextFactory : IDesignTimeDbContextFactory
+{
+ public MovieReviewsDbContext CreateDbContext(string[] args)
+ {
+ var options = new DbContextOptionsBuilder()
+ .UseSqlite(DependencyInjection.DefaultConnectionString)
+ .Options;
+
+ return new MovieReviewsDbContext(options);
+ }
+}
diff --git a/src/Infrastructure/DependencyInjection.cs b/src/Infrastructure/DependencyInjection.cs
index 211ee9b..851d917 100644
--- a/src/Infrastructure/DependencyInjection.cs
+++ b/src/Infrastructure/DependencyInjection.cs
@@ -5,29 +5,72 @@ namespace CleanModelContextProtocol.Infrastructure;
using Application.Movies;
using Application.Reviews;
using Databases.MovieReviews;
+using Databases.MovieReviews.Extensions;
using Databases.MovieReviews.Mapping;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Diagnostics.HealthChecks;
public static class DependencyInjection
{
- public static IServiceCollection AddInfrastructure(this IServiceCollection services)
+ /// The connection string used when none is configured.
+ public const string DefaultConnectionString = "Data Source=movie-reviews.db";
+
+ public static IServiceCollection AddInfrastructure(this IServiceCollection services, string? connectionString = null)
{
- _ = services.AddDbContext(options =>
- options.UseInMemoryDatabase($"Movies-{Guid.NewGuid()}"), ServiceLifetime.Singleton);
+ var database = new MovieReviewsDatabase(string.IsNullOrWhiteSpace(connectionString) ? DefaultConnectionString : connectionString);
+
+ _ = services.AddSingleton(database);
+ _ = services.AddDbContext(options => options.UseSqlite(database.ConnectionString));
_ = services.AddSingleton();
- _ = services.AddSingleton();
+ _ = services.AddScoped();
- _ = services.AddSingleton(p =>
+ _ = services.AddScoped(p =>
p.GetRequiredService());
- _ = services.AddSingleton(x =>
+ _ = services.AddScoped(x =>
x.GetRequiredService());
- _ = services.AddSingleton(x =>
+ _ = services.AddScoped(x =>
x.GetRequiredService());
_ = services.AddSingleton(TimeProvider.System);
return services;
}
+
+ ///
+ /// Adds a readiness check that the movie reviews database can be reached.
+ ///
+ /// The health checks builder.
+ /// The tags to give the check, so endpoints can choose which checks they run.
+ public static IHealthChecksBuilder AddInfrastructureHealthChecks(this IHealthChecksBuilder builder, params string[] tags)
+ {
+ return builder.AddDbContextCheck("MovieReviewsDatabase", HealthStatus.Unhealthy, tags);
+ }
+
+ ///
+ /// Creates or upgrades the database with the migrations. Call it once at startup, before the first request.
+ ///
+ /// The application's services.
+ ///
+ /// Adds the sample authors, movies and reviews when the database is empty. Turn it on for local runs and demos,
+ /// and leave it off anywhere real data lives.
+ ///
+ public static IServiceProvider InitialiseInfrastructure(this IServiceProvider services, bool seedSampleData)
+ {
+ services.GetRequiredService().KeepAlive();
+
+ using var scope = services.CreateScope();
+
+ var context = scope.ServiceProvider.GetRequiredService();
+
+ context.Database.Migrate();
+
+ if (seedSampleData)
+ {
+ _ = context.AddData();
+ }
+
+ return services;
+ }
}
diff --git a/src/Infrastructure/Infrastructure.csproj b/src/Infrastructure/Infrastructure.csproj
index ada2a82..6855f1e 100644
--- a/src/Infrastructure/Infrastructure.csproj
+++ b/src/Infrastructure/Infrastructure.csproj
@@ -5,9 +5,14 @@
-
-
-
+
+
+
+ all
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+
+
+
diff --git a/src/Presentation/Authentication/AuthenticationSettings.cs b/src/Presentation/Authentication/AuthenticationSettings.cs
index e3eecd7..426fdb6 100644
--- a/src/Presentation/Authentication/AuthenticationSettings.cs
+++ b/src/Presentation/Authentication/AuthenticationSettings.cs
@@ -10,10 +10,10 @@ public class AuthenticationSettings
public const string SectionName = "Authentication";
/// The OAuth authorization server that issues access tokens, such as https://login.example.com.
- public string Authority { get; init; }
+ public string? Authority { get; init; }
/// The audience access tokens must be issued for. This is usually the server's own URL.
- public string Audience { get; init; }
+ public string? Audience { get; init; }
/// The scopes clients should ask for, published in the protected resource metadata.
public List Scopes { get; init; } = [];
diff --git a/src/Presentation/Completions/CompletionHandler.cs b/src/Presentation/Completions/CompletionHandler.cs
index 7d690ec..0bd0ec0 100644
--- a/src/Presentation/Completions/CompletionHandler.cs
+++ b/src/Presentation/Completions/CompletionHandler.cs
@@ -17,10 +17,10 @@ public static class CompletionHandler
public static async ValueTask Handle(RequestContext context, CancellationToken cancellationToken)
{
- return await Complete(context.Services.GetRequiredService(), context.Params, cancellationToken);
+ return await Complete(context.Services!.GetRequiredService(), context.Params, cancellationToken);
}
- public static async Task Complete(ISender sender, CompleteRequestParams request, CancellationToken cancellationToken)
+ public static async Task Complete(ISender sender, CompleteRequestParams? request, CancellationToken cancellationToken)
{
var argument = request?.Argument;
@@ -33,7 +33,7 @@ public static async Task Complete(ISender sender, CompleteReques
{
case "movieTitle" or "firstMovieTitle" or "secondMovieTitle":
{
- var page = await sender.Send(new MovieQueries.SearchMovies.SearchMoviesQuery
+ var page = await sender.Send(new MovieQueries.GetMovies.GetMoviesQuery
{
Query = argument.Value,
Limit = Paging.MaxLimit
@@ -44,7 +44,7 @@ public static async Task Complete(ISender sender, CompleteReques
case "authorName":
{
- var page = await sender.Send(new AuthorQueries.SearchAuthors.SearchAuthorsQuery
+ var page = await sender.Send(new AuthorQueries.GetAuthors.GetAuthorsQuery
{
Query = argument.Value,
Limit = Paging.MaxLimit
diff --git a/src/Presentation/Errors/ProtocolErrorFilter.cs b/src/Presentation/Errors/ProtocolErrorFilter.cs
index 98b6ebd..f5675b7 100644
--- a/src/Presentation/Errors/ProtocolErrorFilter.cs
+++ b/src/Presentation/Errors/ProtocolErrorFilter.cs
@@ -25,7 +25,7 @@ public static McpRequestHandler Filter(McpRe
};
}
- public static McpProtocolException ToProtocolException(Exception exception)
+ public static McpProtocolException? ToProtocolException(Exception exception)
{
return exception switch
{
diff --git a/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs b/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs
index f745d2c..796acb2 100644
--- a/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs
+++ b/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs
@@ -36,8 +36,9 @@ public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicat
#region Project Dependencies
_ = builder.Services.AddMediator(options => options.ServiceLifetime = ServiceLifetime.Scoped);
- _ = builder.Services.AddInfrastructure();
+ _ = builder.Services.AddInfrastructure(builder.Configuration.GetConnectionString("MovieReviews"));
_ = builder.Services.AddApplication();
+ _ = builder.Services.AddHealthChecks().AddInfrastructureHealthChecks("ready");
#endregion Project Dependencies
@@ -62,7 +63,7 @@ public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicat
.AddMcp(options => options.ResourceMetadata = new()
{
Resource = authentication.Audience,
- AuthorizationServers = [authentication.Authority],
+ AuthorizationServers = [authentication.Authority!],
ScopesSupported = authentication.Scopes,
ResourceName = "Clean Model Context Protocol"
});
@@ -97,8 +98,8 @@ public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicat
A review links one author to one movie with a star rating from 1 (worst) to 5 (best).
Find things by name first: movies_search and authors_search return ids, review counts and average
stars, and reviews_list filters reviews by movie or author. Every search returns one page at a time,
- so pass nextCursor back to continue rather than raising the limit.
- reviews_write creates a review, or replaces one when you pass its reviewId.
+ so pass nextOffset back as the offset to continue rather than raising the limit.
+ reviews_write creates a review, or changes the stars of one when you pass its reviewId. A review's movie and author can't change.
reviews_delete can't be undone, so confirm with the user before calling it.
Each movie, author and review can also be read as a resource at movies://{id}, authors://{id} or
reviews://{id}, and server://version gives this server's version.
diff --git a/src/Presentation/Extensions/WebApplicationExtensions.cs b/src/Presentation/Extensions/WebApplicationExtensions.cs
index 0fe8b1f..589bd2e 100644
--- a/src/Presentation/Extensions/WebApplicationExtensions.cs
+++ b/src/Presentation/Extensions/WebApplicationExtensions.cs
@@ -2,7 +2,11 @@ namespace CleanModelContextProtocol.Presentation.Extensions;
using System.Diagnostics.CodeAnalysis;
using CleanModelContextProtocol.Presentation.Authentication;
+using Infrastructure;
using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Diagnostics.HealthChecks;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.Hosting;
using Serilog;
[ExcludeFromCodeCoverage]
@@ -10,12 +14,39 @@ public static class WebApplicationExtensions
{
public static WebApplication ConfigureApplication(this WebApplication app)
{
+ #region Database
+
+ _ = app.Services.InitialiseInfrastructure(app.Configuration.GetValue("Database:SeedSampleData"));
+
+ #endregion Database
+
+ #region Security
+
+ // HSTS tells browsers to only use HTTPS from then on, so it's left off for local runs.
+ if (!app.Environment.IsDevelopment() && !app.Environment.IsEnvironment("local"))
+ {
+ _ = app.UseHsts();
+ }
+
+ _ = app.UseHttpsRedirection();
+
+ #endregion Security
+
#region Logging
_ = app.UseSerilogRequestLogging();
#endregion Logging
+ #region Health
+
+ // Liveness runs no checks, so it only fails when the process can't answer. Readiness checks the database.
+ // They aren't behind authorization, so they answer without a token.
+ _ = app.MapHealthChecks("/health/live", new HealthCheckOptions { Predicate = _ => false });
+ _ = app.MapHealthChecks("/health/ready", new HealthCheckOptions { Predicate = check => check.Tags.Contains("ready") });
+
+ #endregion Health
+
#region Model Context Protocol
var mcp = app.MapMcp("/mcp");
diff --git a/src/Presentation/Models/AuthorResult.cs b/src/Presentation/Models/AuthorResult.cs
index b675d1c..f940891 100644
--- a/src/Presentation/Models/AuthorResult.cs
+++ b/src/Presentation/Models/AuthorResult.cs
@@ -15,4 +15,4 @@ public record AuthorResult(
[property: Description("The author's full name.")] string Name,
[property: Description("How many reviews the author has written.")] int ReviewCount,
[property: Description("The average star rating the author gives, from 1 to 5, or null when they have no reviews.")] double? AverageStars,
- [property: Description("Every review the author has written, when they were asked for.")] List Reviews = null);
+ [property: Description("Every review the author has written, when they were asked for.")] List? Reviews = null);
diff --git a/src/Presentation/Models/MovieResult.cs b/src/Presentation/Models/MovieResult.cs
index c857ba1..59f4dfb 100644
--- a/src/Presentation/Models/MovieResult.cs
+++ b/src/Presentation/Models/MovieResult.cs
@@ -15,4 +15,4 @@ public record MovieResult(
[property: Description("The movie's title.")] string Title,
[property: Description("How many reviews the movie has.")] int ReviewCount,
[property: Description("The average star rating, from 1 to 5, or null when there are no reviews.")] double? AverageStars,
- [property: Description("Every review of the movie, when they were asked for.")] List Reviews = null);
+ [property: Description("Every review of the movie, when they were asked for.")] List? Reviews = null);
diff --git a/src/Presentation/Models/ResultMapper.cs b/src/Presentation/Models/ResultMapper.cs
index cd7c3dd..0a01620 100644
--- a/src/Presentation/Models/ResultMapper.cs
+++ b/src/Presentation/Models/ResultMapper.cs
@@ -12,7 +12,7 @@ public static class ResultMapper
{
public static MovieResult ToResult(this Movie movie, bool includeReviews)
{
- var reviews = movie.Reviews ?? [];
+ var reviews = movie.Reviews;
return new MovieResult(
movie.Id,
@@ -22,9 +22,19 @@ public static MovieResult ToResult(this Movie movie, bool includeReviews)
includeReviews ? [.. reviews.Select(r => r.ToResult(movie: new ReviewedMovie(movie.Id, movie.Title)))] : null);
}
+ public static MovieResult ToResult(this MovieSummary movie, IEnumerable? reviews = null)
+ {
+ return new MovieResult(
+ movie.Id,
+ movie.Title,
+ movie.ReviewCount,
+ movie.AverageStars,
+ reviews is null ? null : [.. reviews.Select(r => r.ToResult(movie: new ReviewedMovie(movie.Id, movie.Title)))]);
+ }
+
public static AuthorResult ToResult(this Author author, bool includeReviews)
{
- var reviews = author.Reviews ?? [];
+ var reviews = author.Reviews;
return new AuthorResult(
author.Id,
@@ -34,7 +44,17 @@ public static AuthorResult ToResult(this Author author, bool includeReviews)
includeReviews ? [.. reviews.Select(r => r.ToResult(author: new ReviewAuthor(author.Id, author.FirstName, author.LastName)))] : null);
}
- public static ReviewResult ToResult(this Review review, ReviewedMovie movie = null, ReviewAuthor author = null)
+ public static AuthorResult ToResult(this AuthorSummary author, IEnumerable? reviews = null)
+ {
+ return new AuthorResult(
+ author.Id,
+ FullName(author.FirstName, author.LastName),
+ author.ReviewCount,
+ author.AverageStars,
+ reviews is null ? null : [.. reviews.Select(r => r.ToResult(author: new ReviewAuthor(author.Id, author.FirstName, author.LastName)))]);
+ }
+
+ public static ReviewResult ToResult(this Review review, ReviewedMovie? movie = null, ReviewAuthor? author = null)
{
movie = review.ReviewedMovie ?? movie;
author = review.ReviewAuthor ?? author;
@@ -50,7 +70,9 @@ public static ReviewResult ToResult(this Review review, ReviewedMovie movie = nu
public static ResultPage ToResult(this Page page, Func