Stop throwing for not-found; add Guard and request validation

Not-found lookups return null/false instead of throwing NotFoundException
across all services — a missing row is expected control flow, not an
exceptional condition. NotFoundException stays for embedded precondition
checks inside mutations (missing parent, invalid foreign reference).

Guard (copied from mic-check) enforces required arguments at the top of
every service method. A ported IModelValidator<T> framework validates
every request DTO at the API layer via a new ValidationEndpointFilter,
returning a 400 with field-level messages; services re-run the same
validator and throw for direct callers that bypass the API.

Endpoints translate null/false into 404 via a new ToApiResult() helper.
The agent toolset boundary translates the same nullable/bool results
into the tool-error text the model already expected.
This commit is contained in:
James Wampler
2026-08-06 15:13:36 -07:00
parent 04917fa09e
commit 40f93e40a8
45 changed files with 1523 additions and 377 deletions
@@ -0,0 +1,12 @@
namespace Novelly.Api.Common;
public static class ApiResultExtensions
{
/// <summary>
/// A missing entity is not exceptional, so lookups return null instead of throwing.
/// This is where that null finally becomes an HTTP 404 — the one place the API layer
/// needs to know about it.
/// </summary>
public static IResult ToApiResult<T>(this T? value) where T : class =>
value is null ? Results.NotFound() : Results.Ok(value);
}
+40
View File
@@ -0,0 +1,40 @@
namespace Novelly.Api.Common;
public static class Guard
{
public static void Null<T>(T t, string parameterName) where T : class
{
if (t is null)
throw new ArgumentNullException(parameterName, $"{nameof(parameterName)} can not be null");
}
public static void Empty(string value, string parameterName)
{
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentException($"{parameterName} can not be empty", parameterName);
}
public static void Empty<T>(IEnumerable<T> collection, string parameterName)
{
if (collection == null || !collection.Any())
throw new ArgumentException($"{parameterName} can not be empty", parameterName);
}
public static void Negative(int value, string parameterName)
{
if (value < 0)
throw new ArgumentOutOfRangeException(parameterName, $"{parameterName} must be a positive number or zero");
}
public static void NegativeOrZero(int value, string parameterName)
{
if (value <= 0)
throw new ArgumentOutOfRangeException(parameterName, $"{nameof(parameterName)} must be a positive number greater then zero");
}
public static void Default<T>(T value, string parameterName)
{
if (EqualityComparer<T>.Default.Equals(value, default))
throw new ArgumentException($"{parameterName} can not be a default value", parameterName);
}
}
@@ -3,6 +3,7 @@ using Novelly.Api.Agent;
using Novelly.Api.Beats;
using Novelly.Api.Chapters;
using Novelly.Api.Characters;
using Novelly.Api.Common.Validation;
using Novelly.Api.Data;
using Novelly.Api.Projects;
using Novelly.Api.Questions;
@@ -40,6 +41,8 @@ public static class NovellyServiceRegistration
services.Configure<AgentOptions>(configuration.GetSection(AgentOptions.SectionName));
services.AddScoped<IAgentModelClient, AnthropicAgentModelClient>();
services.AddModelValidatorsFromAssemblyContaining<Program>();
return services;
}
}
@@ -0,0 +1,13 @@
namespace Novelly.Api.Common.Validation;
public interface IModelValidator
{
ValidationResult Validate(object model);
}
public interface IModelValidator<in T> : IModelValidator
{
ValidationResult Validate(T model);
ValidationResult IModelValidator.Validate(object model) => Validate((T)model);
}
@@ -0,0 +1,18 @@
namespace Novelly.Api.Common.Validation;
public static class ModelValidatorServiceCollectionExtensions
{
public static IServiceCollection AddModelValidatorsFromAssemblyContaining<TMarker>(this IServiceCollection services)
{
var registrations = typeof(TMarker).Assembly.GetTypes()
.Where(type => !type.IsAbstract && !type.IsInterface)
.SelectMany(type => type.GetInterfaces()
.Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IModelValidator<>))
.Select(i => (Interface: i, Implementation: type)));
foreach (var (@interface, implementation) in registrations)
services.AddScoped(@interface, implementation);
return services;
}
}
@@ -0,0 +1,38 @@
namespace Novelly.Api.Common.Validation;
/// <summary>
/// Minimal-API equivalent of mic-check's MVC <c>ModelValidationActionFilter</c>. Runs every
/// endpoint argument that has a registered <see cref="IModelValidator{T}"/> through it and,
/// if any fail, short-circuits with a 400 naming every field and message a caller can act on.
/// </summary>
public class ValidationEndpointFilter : IEndpointFilter
{
public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
{
var errors = new Dictionary<string, string[]>();
foreach (var argument in context.Arguments)
{
if (argument is null) continue;
var validatorType = typeof(IModelValidator<>).MakeGenericType(argument.GetType());
if (context.HttpContext.RequestServices.GetService(validatorType) is not IModelValidator validator) continue;
var result = validator.Validate(argument);
if (result.IsInvalid)
{
foreach (var group in result.Errors.GroupBy(e => e.PropertyName))
{
errors[group.Key] = [.. group.Select(e => e.Message)];
}
}
}
if (errors.Count > 0)
{
return Results.ValidationProblem(errors);
}
return await next(context);
}
}
@@ -0,0 +1,14 @@
namespace Novelly.Api.Common.Validation;
public record ValidationError(string PropertyName, string Message);
public class ValidationResult
{
private readonly List<ValidationError> _errors = [];
public IReadOnlyList<ValidationError> Errors => _errors;
public bool IsValid => _errors.Count == 0;
public bool IsInvalid => _errors.Count > 0;
public void AddError(string propertyName, string message) => _errors.Add(new ValidationError(propertyName, message));
}
@@ -0,0 +1,17 @@
namespace Novelly.Api.Common.Validation;
public static class ValidationResultExtensions
{
/// <summary>
/// The service-level half of "validate again and throw if invalid": callers that reach
/// a service directly (agent tools, MCP, tests) skip the API's <see cref="ValidationEndpointFilter"/>,
/// so services re-run the same validator and throw rather than act on bad data.
/// </summary>
public static void ThrowIfInvalid(this ValidationResult result)
{
if (result.IsInvalid)
{
throw new ArgumentException(string.Join("; ", result.Errors.Select(e => $"{e.PropertyName}: {e.Message}")));
}
}
}