Files
Khaemhat/src/Khaemhat.Application/Files/AttachmentService.cs
T
Alby96andClaude Opus 5.5 b341ade9e9 feat: attachments, file store and in-house PDF/CSV/XLSX/ZIP writers (#34)
Documents need attachments and generated files (SPEC 9.4) before the UI of
M3 can show them, and the spec forbids external libraries for PDF and
spreadsheets.

- VolumeFileStore keeps files under <data>/files/<COMPANY>/<yyyy>/<guid>,
  writing a .part file in the same folder with size limit and SHA-256, then
  quota and scanner checks (IFileScanner hook, no-op by default).
- attachments table (migration 007) with kind, version series, lock, trash
  and the uploading user; AttachmentService uploads, adds generated files as
  the next version, lists, opens, zips, locks, trashes, restores and purges
  after 30 days (new system job system.attachments-trash).
- FileGenerationService runs IFileGenerator implementations into the store;
  three generators for the fictitious test document (PDF, CSV, XLSX).
- CsvWriter (Italian Excel defaults, formula-injection guard), XlsxWriter,
  ZipStreamWriter and PdfWriter (standard Type1 fonts, WinAnsi, AFM widths,
  JPEG, Flate, xref) only write asynchronously, so they can stream to an
  HTTP response.
- ADR 0021 records versioning, storage layout, PDF scope and CSV defaults.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 18:06:48 +01:00

733 lines
38 KiB
C#

using System.Data.Common;
using System.Globalization;
using System.Text.RegularExpressions;
using Khaemhat.Application.Audit;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Security;
using Khaemhat.Core.Files;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Infrastructure.Files;
namespace Khaemhat.Application.Files;
/// <summary>An attachment as the interface shows it.</summary>
/// <param name="Id">The identifier.</param>
/// <param name="Entity">The entity of the owning record.</param>
/// <param name="EntityId">The owning record.</param>
/// <param name="Kind">Uploaded, generated, e-invoice or notification.</param>
/// <param name="Name">The name.</param>
/// <param name="FileName">The download name, with the version suffix from v2 (<c>fattura_v2.pdf</c>).</param>
/// <param name="Mime">The media type.</param>
/// <param name="Size">The size in bytes.</param>
/// <param name="Sha256">The SHA-256 of the content.</param>
/// <param name="Version">The version, from 1.</param>
/// <param name="GeneratedBy">The generator code (generated files).</param>
/// <param name="Locked">Whether it is locked (cannot be deleted).</param>
/// <param name="IsLatest">Whether it is the latest version of its series.</param>
/// <param name="CreatedAt">When it was uploaded or generated (UTC).</param>
/// <param name="CreatedBy">Who uploaded or generated it.</param>
/// <param name="DeletedAt">When it was moved to the trash; <see langword="null"/> if in use.</param>
public sealed record AttachmentView(
long Id, string Entity, long EntityId, AttachmentKind Kind, string Name, string FileName, string Mime, long Size, string Sha256,
int Version, string? GeneratedBy, bool Locked, bool IsLatest, DateTime CreatedAt, string? CreatedBy, DateTime? DeletedAt)
{
/// <summary>How the interface can preview the file.</summary>
public AttachmentPreview Preview => MediaTypes.PreviewOf(Mime);
/// <summary>The version label, <c>v1</c>, <c>v2</c>...</summary>
public string VersionLabel => "v" + Version.ToString(CultureInfo.InvariantCulture);
/// <summary>The view of a row.</summary>
/// <param name="row">The row.</param>
/// <param name="isLatest">Whether it is the latest of its series.</param>
/// <returns>The view.</returns>
public static AttachmentView From(Attachment row, bool isLatest)
{
ArgumentNullException.ThrowIfNull(row);
return new AttachmentView(
row.Id, row.Entity, row.EntityId, row.Kind, row.Name, MediaTypes.VersionedFileName(row.Name, row.Version), row.Mime, row.Size, row.Sha256,
row.Version, row.GeneratedBy, row.Locked, isLatest, row.CreatedAt, row.UserName ?? row.CreatedBy, row.DeletedAt);
}
}
/// <summary>An open attachment: its description and its content. Dispose it to close the file.</summary>
/// <param name="attachment">The attachment.</param>
/// <param name="content">The content, a read-only seekable stream.</param>
public sealed class AttachmentContent(AttachmentView attachment, Stream content) : IAsyncDisposable, IDisposable
{
/// <summary>The attachment.</summary>
public AttachmentView Attachment { get; } = attachment;
/// <summary>The content.</summary>
public Stream Content { get; } = content;
/// <inheritdoc />
public ValueTask DisposeAsync() => Content.DisposeAsync();
/// <inheritdoc />
public void Dispose() => Content.Dispose();
}
/// <summary>A file to attach that is not uploaded by a user: an e-invoice, a notification, a file from a procedure.</summary>
/// <param name="Kind">The kind.</param>
/// <param name="FileName">The file name.</param>
/// <param name="Mime">The media type; from the extension when <see langword="null"/>.</param>
/// <param name="GeneratedBy">The procedure that produced it: the versions count per this code when set, per name otherwise.</param>
/// <param name="Locked">Whether it is locked from the start (for example the XML sent to the SDI).</param>
public sealed record AttachmentFile(AttachmentKind Kind, string FileName, string? Mime = null, string? GeneratedBy = null, bool Locked = false);
/// <summary>
/// The attachments of the company records (SPEC §9.4; wiki <i>Allegati e file</i>): upload, generated files with
/// versions, list, download, ZIP of all, lock, trash and restore. An attachment belongs to exactly one record
/// (<c>entity</c> + <c>entity_id</c>); its bytes are in the <see cref="IFileStore"/>, its row in <c>attachments</c>,
/// and every change writes the history (<see cref="AuditTrail"/>).
/// </summary>
/// <remarks>
/// Permissions: reading needs <c>attachments.read</c>, uploading, generating and locking <c>attachments.write</c>,
/// deleting and restoring <c>attachments.delete</c>. The permission on the owning record is checked by the caller (the
/// document service or page), which knows it. A company user works only in its own company. Deleting moves to the
/// company trash; <see cref="PurgeTrashAsync"/> removes rows and files 30 days later.
/// </remarks>
public sealed partial class AttachmentService
{
/// <summary>Permission to see and download attachments.</summary>
public const string ReadPermission = "attachments.read";
/// <summary>Permission to upload and generate attachments.</summary>
public const string WritePermission = "attachments.write";
/// <summary>Permission to delete and restore attachments.</summary>
public const string DeletePermission = "attachments.delete";
/// <summary>The instance setting with the largest upload in MB (default 25).</summary>
public const string MaxUploadSetting = "files.max-upload-mb";
/// <summary>The instance setting with the space each company may use in MB (default: no quota).</summary>
public const string CompanyQuotaSetting = "files.company-quota-mb";
/// <summary>Error: no such attachment (or not in this company).</summary>
public const string NotFoundError = "attachments.not_found";
/// <summary>Error: the attachment is locked.</summary>
public const string LockedError = "attachments.locked";
/// <summary>Error: the file is larger than the limit.</summary>
public const string TooLargeError = "attachments.file_too_large";
/// <summary>Error: the company has no space left.</summary>
public const string QuotaError = "attachments.quota_exceeded";
/// <summary>Error: the scanner rejected the file.</summary>
public const string RejectedError = "attachments.file_rejected";
/// <summary>Error: the entity or record is not valid.</summary>
public const string InvalidOwnerError = "attachments.owner_invalid";
/// <summary>Error: the file is empty.</summary>
public const string EmptyError = "attachments.file_empty";
/// <summary>How long attachments stay in the trash.</summary>
public static readonly TimeSpan TrashRetention = TimeSpan.FromDays(30);
private const int MaxVersionAttempts = 3;
private const long Megabyte = 1024 * 1024;
private readonly IUnitOfWorkFactory _factory;
private readonly IFileStore _store;
private readonly PermissionService _permissions;
private readonly AuditTrail _audit;
private readonly SystemSettingsStore _settings;
private readonly FileStoreOptions _options;
private readonly TimeProvider _clock;
/// <summary>Creates the service.</summary>
/// <param name="factory">Opens the company databases.</param>
/// <param name="store">The file store.</param>
/// <param name="permissions">Checks permissions.</param>
/// <param name="audit">Writes the history.</param>
/// <param name="settings">Reads the limits set by the administrators.</param>
/// <param name="options">The default limits.</param>
/// <param name="clock">The clock (trash dates).</param>
public AttachmentService(
IUnitOfWorkFactory factory, IFileStore store, PermissionService permissions, AuditTrail audit, SystemSettingsStore settings, FileStoreOptions options, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(store);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(audit);
ArgumentNullException.ThrowIfNull(settings);
ArgumentNullException.ThrowIfNull(options);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_store = store;
_permissions = permissions;
_audit = audit;
_settings = settings;
_options = options;
_clock = clock;
}
/// <summary>The limits in force: the instance settings, else the store defaults (25 MB, no quota).</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The limits for uploads.</returns>
public async Task<FileLimits> GetLimitsAsync(CancellationToken cancellationToken = default)
{
var max = await ReadMegabytesAsync(MaxUploadSetting, cancellationToken).ConfigureAwait(false) ?? _options.MaxFileBytes;
var quota = await ReadMegabytesAsync(CompanyQuotaSetting, cancellationToken).ConfigureAwait(false) ?? _options.CompanyQuotaBytes;
return new FileLimits(max, quota);
}
/// <summary>Uploads a file to a record (streaming; the size limit and the quota apply).</summary>
/// <param name="actor">Who uploads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="entity">The entity of the record, for example <c>sales.invoice</c>.</param>
/// <param name="entityId">The record.</param>
/// <param name="fileName">The file name as received.</param>
/// <param name="declaredMime">The type declared by the client (used only when the extension is unknown).</param>
/// <param name="content">The content.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new attachment; a file with the same name as an existing one becomes its next version.</returns>
/// <exception cref="AccessDeniedException">The actor may not upload.</exception>
/// <exception cref="ValidationFailedException">The file is empty, too large, over quota or rejected.</exception>
public async Task<AttachmentView> UploadAsync(
Actor actor, string companyCode, string entity, long entityId, string fileName, string? declaredMime, Stream content, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(content);
var company = await DemandAsync(actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
CheckOwner(entity, entityId);
var limits = await GetLimitsAsync(cancellationToken).ConfigureAwait(false);
var stored = await StoreAsync(company, limits, (target, ct) => content.CopyToAsync(target, ct), cancellationToken).ConfigureAwait(false);
var name = MediaTypes.CleanFileName(fileName);
return await RecordAsync(actor, company, entity, entityId, new AttachmentFile(AttachmentKind.Uploaded, name, MediaTypes.Resolve(name, declaredMime)), stored, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Adds a file produced by Khaemhat, written by <paramref name="write"/> straight into the store. Each call adds
/// the next version of the series of <see cref="AttachmentFile.GeneratedBy"/> (or of the name): this is "Rigenera".
/// </summary>
/// <param name="actor">Who generates.</param>
/// <param name="companyCode">The company.</param>
/// <param name="entity">The entity of the record.</param>
/// <param name="entityId">The record.</param>
/// <param name="file">Kind, name, type, generator, lock.</param>
/// <param name="write">Writes the content to the stream it receives (write-only, not seekable).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new attachment.</returns>
/// <exception cref="AccessDeniedException">The actor may not add attachments.</exception>
/// <exception cref="ValidationFailedException">The company has no space left, or the file is empty.</exception>
public async Task<AttachmentView> AddAsync(
Actor actor, string companyCode, string entity, long entityId, AttachmentFile file, Func<Stream, CancellationToken, Task> write, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(file);
ArgumentNullException.ThrowIfNull(write);
var company = await DemandAsync(actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
CheckOwner(entity, entityId);
if (file.GeneratedBy is { } generator && (generator.Length is 0 or > 100))
{
throw new ValidationFailedException([InvalidOwnerError]);
}
// Files made by Khaemhat are bounded by their generator: only the quota applies.
var limits = await GetLimitsAsync(cancellationToken).ConfigureAwait(false);
var stored = await StoreAsync(company, new FileLimits(0, limits.QuotaBytes), write, cancellationToken).ConfigureAwait(false);
var name = MediaTypes.CleanFileName(file.FileName);
var normalized = file with { FileName = name, Mime = MediaTypes.Resolve(name, file.Mime) };
return await RecordAsync(actor, company, entity, entityId, normalized, stored, cancellationToken).ConfigureAwait(false);
}
/// <summary>The attachments of a record, newest first (trash excluded).</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="entity">The entity.</param>
/// <param name="entityId">The record.</param>
/// <param name="includeOlderVersions">Whether to list the earlier versions too (marked not <see cref="AttachmentView.IsLatest"/>).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The attachments.</returns>
public async Task<IReadOnlyList<AttachmentView>> ListAsync(
Actor actor, string companyCode, string entity, long entityId, bool includeOlderVersions = false, CancellationToken cancellationToken = default)
{
var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
return Views(await ListRowsAsync(company, entity, entityId, cancellationToken).ConfigureAwait(false), includeOlderVersions);
}
/// <summary>How many attachments a record has (latest versions only): the number on the toolbar icon.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="entity">The entity.</param>
/// <param name="entityId">The record.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The count.</returns>
public async Task<int> CountAsync(Actor actor, string companyCode, string entity, long entityId, CancellationToken cancellationToken = default) =>
(await ListAsync(actor, companyCode, entity, entityId, false, cancellationToken).ConfigureAwait(false)).Count;
/// <summary>One attachment, in use or in the trash.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="attachmentId">The attachment.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The attachment, or <see langword="null"/>.</returns>
public async Task<AttachmentView?> GetAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default)
{
var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
return (await LoadAsync(company, attachmentId, cancellationToken).ConfigureAwait(false))?.View;
}
/// <summary>Opens an attachment for download or preview.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="attachmentId">The attachment.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The attachment and its content; dispose it.</returns>
/// <exception cref="KeyNotFoundException">No such attachment in use, or its file is missing.</exception>
public async Task<AttachmentContent> OpenAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default)
{
var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
var loaded = await LoadAsync(company, attachmentId, cancellationToken).ConfigureAwait(false);
if (loaded is not { } found || found.Row.DeletedAt is not null)
{
throw new KeyNotFoundException(NotFoundError);
}
var (row, view) = found;
try
{
return new AttachmentContent(view, _store.OpenRead(company, row.StorageKey));
}
catch (FileStoreException ex) when (ex.Code == FileStoreException.NotFound)
{
throw new KeyNotFoundException(NotFoundError, ex);
}
}
/// <summary>
/// Writes a ZIP with the latest version of every attachment of a record ("Scarica tutto"), streaming: the output
/// can be the HTTP response.
/// </summary>
/// <param name="actor">Who downloads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="entity">The entity.</param>
/// <param name="entityId">The record.</param>
/// <param name="output">The stream that receives the ZIP; it is left open.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>How many files were written.</returns>
public async Task<int> WriteZipAsync(Actor actor, string companyCode, string entity, long entityId, Stream output, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(output);
var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
var rows = await ListRowsAsync(company, entity, entityId, cancellationToken).ConfigureAwait(false);
var keys = rows.ToDictionary(r => r.Id, r => r.StorageKey);
await using var zip = await ZipStreamWriter.CreateAsync(output, leaveOpen: true, cancellationToken).ConfigureAwait(false);
foreach (var attachment in Views(rows, includeOlderVersions: false))
{
var key = keys[attachment.Id];
if (!_store.Exists(company, key))
{
continue;
}
var content = _store.OpenRead(company, key);
await using (content.ConfigureAwait(false))
{
var level = attachment.Mime is "image/jpeg" or "image/png" or MediaTypes.Zip or MediaTypes.Xlsx
? System.IO.Compression.CompressionLevel.NoCompression
: System.IO.Compression.CompressionLevel.Optimal;
await zip.AddAsync(attachment.FileName, content, new DateTimeOffset(DateTime.SpecifyKind(attachment.CreatedAt, DateTimeKind.Utc)), level, cancellationToken).ConfigureAwait(false);
}
}
return zip.Count;
}
/// <summary>Locks an attachment: from now on it cannot be deleted (for example the XML sent to the SDI). Locks are permanent.</summary>
/// <param name="actor">Who locks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="attachmentId">The attachment.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task LockAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default) =>
ChangeAsync(
actor, companyCode, attachmentId, WritePermission,
row =>
{
if (row.Locked)
{
return false;
}
row.Locked = true;
return true;
},
cancellationToken);
/// <summary>Moves one attachment to the company trash (restorable for 30 days).</summary>
/// <param name="actor">Who deletes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="attachmentId">The attachment.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
/// <exception cref="ValidationFailedException">The attachment is locked (<see cref="LockedError"/>).</exception>
public Task DeleteAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default)
{
var now = _clock.GetUtcNow().UtcDateTime;
return ChangeAsync(
actor, companyCode, attachmentId, DeletePermission,
row =>
{
if (row.Locked)
{
throw new ValidationFailedException([LockedError]);
}
if (row.DeletedAt is not null)
{
return false;
}
row.DeletedAt = now;
return true;
},
cancellationToken);
}
/// <summary>Takes an attachment back from the trash.</summary>
/// <param name="actor">Who restores.</param>
/// <param name="companyCode">The company.</param>
/// <param name="attachmentId">The attachment.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task RestoreAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default) =>
ChangeAsync(
actor, companyCode, attachmentId, DeletePermission,
row =>
{
if (row.DeletedAt is null)
{
return false;
}
row.DeletedAt = null;
return true;
},
cancellationToken);
/// <summary>
/// Moves every attachment of a record to the trash: call it in the deletion of the record (the caller has checked
/// that the record may be deleted). Refused when an attachment is locked: a record with a sent e-invoice cannot go.
/// </summary>
/// <param name="actor">Who deletes the record.</param>
/// <param name="companyCode">The company.</param>
/// <param name="entity">The entity.</param>
/// <param name="entityId">The record.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>How many attachments were moved.</returns>
/// <exception cref="ValidationFailedException">An attachment is locked (<see cref="LockedError"/>).</exception>
public Task<int> TrashForEntityAsync(Actor actor, string companyCode, string entity, long entityId, CancellationToken cancellationToken = default) =>
ChangeEntityAsync(actor, companyCode, entity, entityId, toTrash: true, cancellationToken);
/// <summary>Takes back from the trash every attachment of a record (the record was restored).</summary>
/// <param name="actor">Who restores.</param>
/// <param name="companyCode">The company.</param>
/// <param name="entity">The entity.</param>
/// <param name="entityId">The record.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>How many attachments were restored.</returns>
public Task<int> RestoreForEntityAsync(Actor actor, string companyCode, string entity, long entityId, CancellationToken cancellationToken = default) =>
ChangeEntityAsync(actor, companyCode, entity, entityId, toTrash: false, cancellationToken);
/// <summary>The company trash, most recently deleted first.</summary>
/// <param name="actor">Who looks (needs <c>attachments.delete</c>).</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The attachments in the trash.</returns>
public async Task<IReadOnlyList<AttachmentView>> ListTrashAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await DemandAsync(actor, companyCode, DeletePermission, cancellationToken).ConfigureAwait(false);
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var rows = (await unitOfWork.Repository<Attachment, long>().ListAsync(
Query.For<Attachment>().Where(a => a.DeletedAt != null).OrderByDescending(a => a.DeletedAt).Take(1000), cancellationToken).ConfigureAwait(false)).Items;
return rows.Select(r => AttachmentView.From(r, isLatest: false)).ToList();
}
/// <summary>The space the company uses in the file store, with the quota in force.</summary>
/// <param name="actor">Who looks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The usage.</returns>
public async Task<FileUsage> GetUsageAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
var limits = await GetLimitsAsync(cancellationToken).ConfigureAwait(false);
return await _store.GetUsageAsync(company, limits.QuotaBytes, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Removes for good the attachments in the trash for more than 30 days, rows and files, and the partial files of
/// interrupted uploads. Run by the scheduled job <see cref="AttachmentTrashPurgeJob"/>.
/// </summary>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>How many attachments were removed.</returns>
public async Task<int> PurgeTrashAsync(string companyCode, CancellationToken cancellationToken = default)
{
var company = CompanyCodes.Normalize(companyCode);
var limit = _clock.GetUtcNow().UtcDateTime - TrashRetention;
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var repository = unitOfWork.Repository<Attachment, long>();
var rows = (await repository.ListAsync(Query.For<Attachment>().Where(a => a.DeletedAt != null && a.DeletedAt < limit), cancellationToken).ConfigureAwait(false)).Items;
var removed = 0;
foreach (var row in rows)
{
await unitOfWork.InTransactionAsync(
async ct =>
{
await repository.DeleteAsync(row.Id, ct).ConfigureAwait(false);
await _audit.RecordAsync(unitOfWork, AuditAction.Delete, row.Id, row, null, Actor.System.UserName, ct).ConfigureAwait(false);
},
cancellationToken).ConfigureAwait(false);
// The row is gone: the file follows (a file left behind by a crash here is only wasted space).
if (!await StorageKeyInUseAsync(repository, row.StorageKey, cancellationToken).ConfigureAwait(false))
{
_store.Delete(company, row.StorageKey);
}
removed++;
}
_store.DeleteAbandonedParts(company, TimeSpan.FromDays(1));
return removed;
}
private static List<AttachmentView> Views(IReadOnlyList<Attachment> rows, bool includeOlderVersions)
{
var latest = rows.GroupBy(r => r.VersionKey, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.Max(r => r.Version), StringComparer.Ordinal);
return rows
.Select(r => AttachmentView.From(r, r.Version == latest[r.VersionKey]))
.Where(v => includeOlderVersions || v.IsLatest)
.ToList();
}
private static void CheckOwner(string entity, long entityId)
{
if (entity is null || entity.Length > 100 || !EntityPattern().IsMatch(entity) || entityId <= 0)
{
throw new ValidationFailedException([InvalidOwnerError]);
}
}
private static string VersionKeyOf(AttachmentFile file) =>
file.GeneratedBy is { } generator ? "gen:" + generator : "name:" + file.FileName.ToLowerInvariant();
private static async Task<bool> IsLatestAsync(IUnitOfWork unitOfWork, Attachment row, CancellationToken cancellationToken)
{
var (entity, id, key, version) = (row.Entity, row.EntityId, row.VersionKey, row.Version);
return await unitOfWork.Repository<Attachment, long>().CountAsync(
Query.For<Attachment>().Where(a => a.Entity == entity && a.EntityId == id && a.VersionKey == key && a.Version > version),
cancellationToken).ConfigureAwait(false) == 0;
}
private static async Task<bool> StorageKeyInUseAsync(IRepository<Attachment, long> repository, string key, CancellationToken cancellationToken) =>
await repository.CountAsync(Query.For<Attachment>().Where(a => a.StorageKey == key), cancellationToken).ConfigureAwait(false) > 0;
[GeneratedRegex("^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_-]*)*$", RegexOptions.CultureInvariant)]
private static partial Regex EntityPattern();
private async Task<string> DemandAsync(Actor actor, string companyCode, string permission, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(actor);
var company = CompanyCodes.Normalize(companyCode);
if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, company, StringComparison.Ordinal))
{
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company.");
}
await _permissions.DemandAsync(actor, permission, cancellationToken).ConfigureAwait(false);
return company;
}
private async Task<long?> ReadMegabytesAsync(string key, CancellationToken cancellationToken)
{
var value = await _settings.GetAsync(key, cancellationToken).ConfigureAwait(false);
return long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var megabytes) && megabytes >= 0 ? megabytes * Megabyte : null;
}
private async Task<StoredFile> StoreAsync(string company, FileLimits limits, Func<Stream, CancellationToken, Task> write, CancellationToken cancellationToken)
{
try
{
await using var writer = await _store.CreateAsync(company, limits, cancellationToken).ConfigureAwait(false);
await write(writer.Content, cancellationToken).ConfigureAwait(false);
if (writer.Content.Length == 0)
{
throw new ValidationFailedException([EmptyError]);
}
return await writer.CommitAsync(cancellationToken).ConfigureAwait(false);
}
catch (FileStoreException ex)
{
var code = ex.Code switch
{
FileStoreException.TooLarge => TooLargeError,
FileStoreException.QuotaExceeded => QuotaError,
_ => RejectedError,
};
throw new ValidationFailedException(code, ex);
}
}
private async Task<AttachmentView> RecordAsync(
Actor actor, string company, string entity, long entityId, AttachmentFile file, StoredFile stored, CancellationToken cancellationToken)
{
var key = VersionKeyOf(file);
try
{
for (var attempt = 1; ; attempt++)
{
try
{
return await InsertAsync(actor, company, entity, entityId, file, key, stored, cancellationToken).ConfigureAwait(false);
}
catch (DbException) when (attempt < MaxVersionAttempts)
{
// Two versions of the same series at once: the unique index refused one; take the next number.
}
}
}
catch
{
_store.Delete(company, stored.Key);
throw;
}
}
private async Task<AttachmentView> InsertAsync(
Actor actor, string company, string entity, long entityId, AttachmentFile file, string key, StoredFile stored, CancellationToken cancellationToken)
{
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var repository = unitOfWork.Repository<Attachment, long>();
Attachment? row = null;
await unitOfWork.InTransactionAsync(
async ct =>
{
var last = await repository.FindAsync(
Query.For<Attachment>().Where(a => a.Entity == entity && a.EntityId == entityId && a.VersionKey == key).OrderByDescending(a => a.Version).Take(1),
ct).ConfigureAwait(false);
row = new Attachment
{
Entity = entity,
EntityId = entityId,
Kind = file.Kind,
Name = file.FileName,
Mime = file.Mime ?? MediaTypes.OctetStream,
Size = stored.Size,
Sha256 = stored.Sha256,
Version = (last?.Version ?? 0) + 1,
VersionKey = key,
GeneratedBy = file.GeneratedBy,
StorageKey = stored.Key,
UserName = actor.UserName.Length > 100 ? actor.UserName[..100] : actor.UserName,
Locked = file.Locked,
};
await repository.InsertAsync(row, ct).ConfigureAwait(false);
await _audit.RecordAsync(unitOfWork, AuditAction.Insert, row.Id, null, row, actor.UserName, ct).ConfigureAwait(false);
},
cancellationToken).ConfigureAwait(false);
return AttachmentView.From(row!, isLatest: true);
}
private async Task ChangeAsync(Actor actor, string companyCode, long attachmentId, string permission, Func<Attachment, bool> change, CancellationToken cancellationToken)
{
var company = await DemandAsync(actor, companyCode, permission, cancellationToken).ConfigureAwait(false);
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var repository = unitOfWork.Repository<Attachment, long>();
await unitOfWork.InTransactionAsync(
async ct =>
{
var row = await repository.GetAsync(attachmentId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFoundError);
var before = Copy(row);
if (change(row))
{
await repository.UpdateAsync(row, ct).ConfigureAwait(false);
await _audit.RecordAsync(unitOfWork, AuditAction.Update, row.Id, before, row, actor.UserName, ct).ConfigureAwait(false);
}
},
cancellationToken).ConfigureAwait(false);
}
private async Task<int> ChangeEntityAsync(Actor actor, string companyCode, string entity, long entityId, bool toTrash, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(actor);
var company = CompanyCodes.Normalize(companyCode);
if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, company, StringComparison.Ordinal))
{
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company.");
}
CheckOwner(entity, entityId);
var now = _clock.GetUtcNow().UtcDateTime;
var changed = 0;
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var repository = unitOfWork.Repository<Attachment, long>();
await unitOfWork.InTransactionAsync(
async ct =>
{
var query = toTrash
? Query.For<Attachment>().Where(a => a.Entity == entity && a.EntityId == entityId && a.DeletedAt == null)
: Query.For<Attachment>().Where(a => a.Entity == entity && a.EntityId == entityId && a.DeletedAt != null);
var rows = (await repository.ListAsync(query, ct).ConfigureAwait(false)).Items;
if (toTrash && rows.Any(r => r.Locked))
{
throw new ValidationFailedException([LockedError]);
}
foreach (var row in rows)
{
var before = Copy(row);
row.DeletedAt = toTrash ? now : null;
await repository.UpdateAsync(row, ct).ConfigureAwait(false);
await _audit.RecordAsync(unitOfWork, AuditAction.Update, row.Id, before, row, actor.UserName, ct).ConfigureAwait(false);
changed++;
}
},
cancellationToken).ConfigureAwait(false);
return changed;
}
private async Task<IReadOnlyList<Attachment>> ListRowsAsync(string company, string entity, long entityId, CancellationToken cancellationToken)
{
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return (await unitOfWork.Repository<Attachment, long>().ListAsync(
Query.For<Attachment>().Where(a => a.Entity == entity && a.EntityId == entityId && a.DeletedAt == null).OrderByDescending(a => a.Id),
cancellationToken).ConfigureAwait(false)).Items;
}
private async Task<(Attachment Row, AttachmentView View)?> LoadAsync(string company, long attachmentId, CancellationToken cancellationToken)
{
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var row = await unitOfWork.Repository<Attachment, long>().GetAsync(attachmentId, cancellationToken).ConfigureAwait(false);
return row is null ? null : (row, AttachmentView.From(row, await IsLatestAsync(unitOfWork, row, cancellationToken).ConfigureAwait(false)));
}
private static Attachment Copy(Attachment row) => new()
{
Id = row.Id,
Entity = row.Entity,
EntityId = row.EntityId,
Kind = row.Kind,
Name = row.Name,
Mime = row.Mime,
Size = row.Size,
Sha256 = row.Sha256,
Version = row.Version,
VersionKey = row.VersionKey,
GeneratedBy = row.GeneratedBy,
StorageKey = row.StorageKey,
UserName = row.UserName,
Locked = row.Locked,
DeletedAt = row.DeletedAt,
};
}