diff --git a/src/MemeVault.Api/Middleware/DomainExceptionHandler.cs b/src/MemeVault.Api/Middleware/DomainExceptionHandler.cs
index 6c12a22..48ce5c5 100644
--- a/src/MemeVault.Api/Middleware/DomainExceptionHandler.cs
+++ b/src/MemeVault.Api/Middleware/DomainExceptionHandler.cs
@@ -5,7 +5,11 @@ using Microsoft.AspNetCore.Mvc;
namespace MemeVault.Api.Middleware;
///
-/// Конвертирует DomainException в 400 Problem Details.
+/// Конвертирует DomainException и наследников в Problem Details:
+///
+/// - → 403
+/// - Все остальные → 400
+///
///
public sealed class DomainExceptionHandler : IExceptionHandler
{
@@ -17,14 +21,18 @@ public sealed class DomainExceptionHandler : IExceptionHandler
if (ex is not DomainException domain)
return false;
+ var status = domain is InsufficientPermissionException
+ ? StatusCodes.Status403Forbidden
+ : StatusCodes.Status400BadRequest;
+
var problem = new ProblemDetails
{
- Title = "Business rule violation",
+ Title = domain is InsufficientPermissionException ? "Forbidden" : "Business rule violation",
Detail = domain.Message,
- Status = StatusCodes.Status400BadRequest,
+ Status = status,
};
- ctx.Response.StatusCode = problem.Status!.Value;
+ ctx.Response.StatusCode = status;
await ctx.Response.WriteAsJsonAsync(problem, ct);
return true;
}
diff --git a/src/MemeVault.Application/Commands/DeleteCollection/DeleteCollectionCommandHandler.cs b/src/MemeVault.Application/Commands/DeleteCollection/DeleteCollectionCommandHandler.cs
index c168421..72c6775 100644
--- a/src/MemeVault.Application/Commands/DeleteCollection/DeleteCollectionCommandHandler.cs
+++ b/src/MemeVault.Application/Commands/DeleteCollection/DeleteCollectionCommandHandler.cs
@@ -20,7 +20,7 @@ public sealed class DeleteCollectionCommandHandler(
var user = await users.GetByTelegramIdAsync(request.RequestingTelegramId, ct);
if (user?.InboxCollectionId == collection.Id)
- throw new DomainException("Cannot delete the Inbox collection.");
+ throw new InboxProtectionException("Cannot delete the Inbox collection.");
collection.Delete(request.RequestingTelegramId);
await collections.RemoveAsync(collection, ct);
diff --git a/src/MemeVault.Application/Commands/SetCollectionInbox/SetCollectionInboxCommandHandler.cs b/src/MemeVault.Application/Commands/SetCollectionInbox/SetCollectionInboxCommandHandler.cs
index b397db4..c529807 100644
--- a/src/MemeVault.Application/Commands/SetCollectionInbox/SetCollectionInboxCommandHandler.cs
+++ b/src/MemeVault.Application/Commands/SetCollectionInbox/SetCollectionInboxCommandHandler.cs
@@ -22,7 +22,7 @@ public sealed class SetCollectionInboxCommandHandler(
if (user is null) return false;
if (user.InboxCollectionId == target.Id)
- throw new DomainException("Collection is already the Inbox.");
+ throw new InboxProtectionException("Collection is already the Inbox.");
user.SetInboxCollection(target.Id);
await users.UpdateAsync(user, ct);
diff --git a/src/MemeVault.Application/Commands/UpdateCollection/UpdateCollectionCommandHandler.cs b/src/MemeVault.Application/Commands/UpdateCollection/UpdateCollectionCommandHandler.cs
index b4768b5..1734f6f 100644
--- a/src/MemeVault.Application/Commands/UpdateCollection/UpdateCollectionCommandHandler.cs
+++ b/src/MemeVault.Application/Commands/UpdateCollection/UpdateCollectionCommandHandler.cs
@@ -1,13 +1,11 @@
using MediatR;
using MemeVault.Application.Common;
-using MemeVault.Domain.Exceptions;
using MemeVault.Domain.Repositories;
namespace MemeVault.Application.Commands.UpdateCollection;
public sealed class UpdateCollectionCommandHandler(
ICollectionRepository collections,
- IBotUserRepository users,
IUnitOfWork unitOfWork)
: IRequestHandler
{
@@ -15,14 +13,10 @@ public sealed class UpdateCollectionCommandHandler(
{
var collection = await collections.GetByIdAsync(request.CollectionId, ct);
// Если коллекции нет или пользователь — не участник, возвращаем 404.
- // Если роль ниже Manager — domain.Rename() бросит DomainException.
+ // Если роль ниже Manager — domain.Rename() бросит InsufficientPermissionException.
if (collection is null || collection.GetRole(request.RequestingTelegramId) is null)
return false;
- var user = await users.GetByTelegramIdAsync(request.RequestingTelegramId, ct);
- if (user?.InboxCollectionId == collection.Id)
- throw new DomainException("Cannot rename the Inbox collection.");
-
collection.Rename(request.Name, request.RequestingTelegramId);
await unitOfWork.SaveChangesAsync(ct);
return true;
diff --git a/src/MemeVault.Application/Queries/GetMediaDownloadUrl/GetMediaDownloadUrlQueryHandler.cs b/src/MemeVault.Application/Queries/GetMediaDownloadUrl/GetMediaDownloadUrlQueryHandler.cs
index c8528b8..ae1c56f 100644
--- a/src/MemeVault.Application/Queries/GetMediaDownloadUrl/GetMediaDownloadUrlQueryHandler.cs
+++ b/src/MemeVault.Application/Queries/GetMediaDownloadUrl/GetMediaDownloadUrlQueryHandler.cs
@@ -13,14 +13,17 @@ public sealed class GetMediaDownloadUrlQueryHandler
private static readonly TimeSpan UrlExpiry = TimeSpan.FromMinutes(15);
private readonly IMediaItemRepository _mediaItems;
- private readonly ITelegramFileCacheService _cache;
+ private readonly ITelegramFileCacheService _telegramCache;
+ private readonly IFileStorage _fileStorage;
public GetMediaDownloadUrlQueryHandler(
IMediaItemRepository mediaItems,
- ITelegramFileCacheService cache)
+ ITelegramFileCacheService telegramCache,
+ IFileStorage fileStorage)
{
- _mediaItems = mediaItems;
- _cache = cache;
+ _mediaItems = mediaItems;
+ _telegramCache = telegramCache;
+ _fileStorage = fileStorage;
}
public async Task Handle(GetMediaDownloadUrlQuery request, CancellationToken ct)
@@ -29,18 +32,18 @@ public sealed class GetMediaDownloadUrlQueryHandler
?? throw new DomainException("Media item not found.");
if (item.OwnerTelegramId != request.RequestingUserTelegramId)
- throw new DomainException("Access denied.");
+ throw new InsufficientPermissionException("Access denied.");
if (item.Type == MediaType.Text || item.Source is null)
throw new DomainException("This media item has no downloadable file.");
if (item.Source.Origin == MediaOrigin.S3)
{
- // Already stored in S3 — just generate a presigned URL directly.
- return await _cache.GetCachedUrlAsync(item.Source.Reference!, UrlExpiry, ct);
+ // File is already stored in S3 — generate presigned URL directly.
+ return await _fileStorage.GetDownloadUrlAsync(item.Source.Reference!, UrlExpiry, ct);
}
- // Telegram source — go through cache (lock → S3 check → fetch → upload → presign).
- return await _cache.GetCachedUrlAsync(item.Source.Reference!, UrlExpiry, ct);
+ // Telegram source — fetch, cache in S3, and return presigned URL.
+ return await _telegramCache.GetCachedUrlAsync(item.Source.Reference!, UrlExpiry, ct);
}
}
diff --git a/src/MemeVault.Domain/Aggregates/Collection/Collection.cs b/src/MemeVault.Domain/Aggregates/Collection/Collection.cs
index fa31578..b43c6d2 100644
--- a/src/MemeVault.Domain/Aggregates/Collection/Collection.cs
+++ b/src/MemeVault.Domain/Aggregates/Collection/Collection.cs
@@ -52,10 +52,10 @@ public sealed class Collection
public static Collection Create(long ownerTelegramId, string name, string? description = null)
{
if (string.IsNullOrWhiteSpace(name))
- throw new DomainException("Collection name cannot be empty.");
+ throw new DomainValidationException("Collection name cannot be empty.");
if (name.Length > 100)
- throw new DomainException("Collection name must be 100 characters or less.");
+ throw new DomainValidationException("Collection name must be 100 characters or less.");
return new Collection(Guid.NewGuid(), ownerTelegramId, name, description);
}
@@ -71,7 +71,7 @@ public sealed class Collection
EnsureRole(requestingTelegramId, CollectionRole.Owner);
if (role == CollectionRole.Owner)
- throw new DomainException("Cannot assign Owner role. Transfer ownership instead.");
+ throw new InsufficientPermissionException("Cannot assign Owner role. Transfer ownership instead.");
var existing = _members.FirstOrDefault(m => m.TelegramId == telegramId);
if (existing is not null)
@@ -129,7 +129,7 @@ public sealed class Collection
EnsureRole(requestingTelegramId, CollectionRole.Manager);
if (string.IsNullOrWhiteSpace(newName))
- throw new DomainException("Collection name cannot be empty.");
+ throw new DomainValidationException("Collection name cannot be empty.");
Name = newName.Trim();
UpdatedAt = DateTimeOffset.UtcNow;
@@ -219,7 +219,7 @@ public sealed class Collection
{
var role = GetRole(telegramId);
if (role is null || role < minimumRole)
- throw new DomainException($"Action requires at least {minimumRole} role.");
+ throw new InsufficientPermissionException($"Action requires at least {minimumRole} role.");
}
private static string GenerateToken() =>
diff --git a/src/MemeVault.Domain/Aggregates/CollectionInvite/CollectionInvite.cs b/src/MemeVault.Domain/Aggregates/CollectionInvite/CollectionInvite.cs
index 95f64e9..ccea8bc 100644
--- a/src/MemeVault.Domain/Aggregates/CollectionInvite/CollectionInvite.cs
+++ b/src/MemeVault.Domain/Aggregates/CollectionInvite/CollectionInvite.cs
@@ -52,10 +52,10 @@ public sealed class CollectionInvite
DateTimeOffset? expiresAt = null)
{
if (role == CollectionRole.Owner)
- throw new DomainException("Cannot create an invite with Owner role.");
+ throw new InsufficientPermissionException("Cannot create an invite with Owner role.");
if (expiresAt.HasValue && expiresAt.Value <= DateTimeOffset.UtcNow)
- throw new DomainException("Invite expiry must be in the future.");
+ throw new DomainValidationException("Invite expiry must be in the future.");
return new CollectionInvite(collectionId, createdBy, role, expiresAt);
}
diff --git a/src/MemeVault.Domain/Aggregates/MediaItem/MediaItem.cs b/src/MemeVault.Domain/Aggregates/MediaItem/MediaItem.cs
index d4271df..56da2e4 100644
--- a/src/MemeVault.Domain/Aggregates/MediaItem/MediaItem.cs
+++ b/src/MemeVault.Domain/Aggregates/MediaItem/MediaItem.cs
@@ -75,10 +75,10 @@ public sealed class MediaItem
IEnumerable? tags = null)
{
if (type == MediaType.Text && string.IsNullOrWhiteSpace(caption))
- throw new DomainException("Text media must have non-empty caption.");
+ throw new DomainValidationException("Text media must have non-empty caption.");
if (type != MediaType.Text && source is null)
- throw new DomainException("Non-text media must have a source (Telegram fileId or S3 key).");
+ throw new DomainValidationException("Non-text media must have a source (Telegram fileId or S3 key).");
var item = new MediaItem(
Guid.NewGuid(),
@@ -111,7 +111,7 @@ public sealed class MediaItem
{
if (_tags.Contains(tag)) return;
if (_tags.Count >= 20)
- throw new DomainException("Cannot have more than 20 tags per item.");
+ throw new DomainValidationException("Cannot have more than 20 tags per item.");
_tags.Add(tag);
UpdatedAt = DateTimeOffset.UtcNow;
@@ -128,7 +128,7 @@ public sealed class MediaItem
{
var distinct = newTags.Distinct().ToList();
if (distinct.Count > 20)
- throw new DomainException("Cannot have more than 20 tags per item.");
+ throw new DomainValidationException("Cannot have more than 20 tags per item.");
_tags.Clear();
_tags.AddRange(distinct);
diff --git a/src/MemeVault.Domain/Exceptions/DomainValidationException.cs b/src/MemeVault.Domain/Exceptions/DomainValidationException.cs
new file mode 100644
index 0000000..7912462
--- /dev/null
+++ b/src/MemeVault.Domain/Exceptions/DomainValidationException.cs
@@ -0,0 +1,11 @@
+namespace MemeVault.Domain.Exceptions;
+
+///
+/// Выбрасывается при нарушении инвариантов формата данных:
+/// пустые строки, превышение длины, недопустимые значения.
+/// API-слой преобразует в HTTP 400.
+///
+public sealed class DomainValidationException : DomainException
+{
+ public DomainValidationException(string message) : base(message) { }
+}
diff --git a/src/MemeVault.Domain/Exceptions/InboxProtectionException.cs b/src/MemeVault.Domain/Exceptions/InboxProtectionException.cs
new file mode 100644
index 0000000..191366f
--- /dev/null
+++ b/src/MemeVault.Domain/Exceptions/InboxProtectionException.cs
@@ -0,0 +1,11 @@
+namespace MemeVault.Domain.Exceptions;
+
+///
+/// Выбрасывается при попытке выполнить запрещённую операцию над Inbox-коллекцией:
+/// удалить, переименовать или назначить уже активный Inbox повторно.
+/// API-слой преобразует в HTTP 400.
+///
+public sealed class InboxProtectionException : DomainException
+{
+ public InboxProtectionException(string message) : base(message) { }
+}
diff --git a/src/MemeVault.Domain/Exceptions/InsufficientPermissionException.cs b/src/MemeVault.Domain/Exceptions/InsufficientPermissionException.cs
new file mode 100644
index 0000000..214fbc7
--- /dev/null
+++ b/src/MemeVault.Domain/Exceptions/InsufficientPermissionException.cs
@@ -0,0 +1,11 @@
+namespace MemeVault.Domain.Exceptions;
+
+///
+/// Выбрасывается, когда у пользователя недостаточно прав для выполнения операции
+/// (недостаточная роль в коллекции или полный отказ в доступе).
+/// API-слой преобразует в HTTP 403.
+///
+public sealed class InsufficientPermissionException : DomainException
+{
+ public InsufficientPermissionException(string message) : base(message) { }
+}
diff --git a/src/MemeVault.Domain/ValueObjects/Tag.cs b/src/MemeVault.Domain/ValueObjects/Tag.cs
index 8ca05ec..a23fce8 100644
--- a/src/MemeVault.Domain/ValueObjects/Tag.cs
+++ b/src/MemeVault.Domain/ValueObjects/Tag.cs
@@ -9,12 +9,12 @@ public sealed record Tag
public Tag(string value)
{
if (string.IsNullOrWhiteSpace(value))
- throw new DomainException("Tag cannot be empty.");
+ throw new DomainValidationException("Tag cannot be empty.");
Value = value.Trim().ToLowerInvariant();
if (Value.Length > 50)
- throw new DomainException("Tag must be 50 characters or less.");
+ throw new DomainValidationException("Tag must be 50 characters or less.");
}
public static implicit operator string(Tag tag) => tag.Value;
diff --git a/src/MemeVault.Domain/ValueObjects/TelegramFileId.cs b/src/MemeVault.Domain/ValueObjects/TelegramFileId.cs
index 3572015..ceedc4c 100644
--- a/src/MemeVault.Domain/ValueObjects/TelegramFileId.cs
+++ b/src/MemeVault.Domain/ValueObjects/TelegramFileId.cs
@@ -13,7 +13,7 @@ public sealed record TelegramFileId
public TelegramFileId(string value)
{
if (string.IsNullOrWhiteSpace(value))
- throw new DomainException("FileId cannot be empty.");
+ throw new DomainValidationException("FileId cannot be empty.");
Value = value;
}