Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ public sealed record AttachmentOptions
{
public const string SectionName = "Attachments";

/// <summary>The longest <see cref="AddTimeout"/>. The grace of the sweep of the bucket grows with it.</summary>
public static readonly TimeSpan LongestAddTimeout = TimeSpan.FromHours(1);

/// <summary>
/// The longest time of one add, from the start of its put to the end of the save of its row. At this time the add
/// stops its put or its save, and throws a <see cref="TimeoutException"/>.
Expand All @@ -15,8 +18,8 @@ public sealed record AttachmentOptions
public static AttachmentOptions From(IConfiguration configuration)
{
var options = configuration.GetSection(SectionName).Get<AttachmentOptions>() ?? new AttachmentOptions();
if (options.AddTimeout <= TimeSpan.Zero)
throw new InvalidOperationException($"{SectionName}:AddTimeout must be over zero.");
if (options.AddTimeout <= TimeSpan.Zero || options.AddTimeout > LongestAddTimeout)
throw new InvalidOperationException($"{SectionName}:AddTimeout must be over zero and at most {LongestAddTimeout}.");
return options;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ namespace FullstackTemplate.Server.Domain.ObjectDeletes;
using Databases.EntityConfigurations;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Resources;

/// <summary>
/// The keys that the live rows name in each <see cref="StoredFile"/> column. The columns come from the EF model, so a
Expand Down Expand Up @@ -51,7 +52,18 @@ private static LoadKeys LoaderOf<TEntity>(StorageKeyColumn column)
column.PathToKey.Aggregate((Expression)row, Expression.MakeMemberAccess), row);
var operationName = $"object_sweep.load_named_{column.EntityType.GetTableName() ?? column.EntityType.ClrType.Name}"
+ $".{column.StorageKey.GetColumnName()}";
return (dbContext, keys, cancellationToken) => dbContext.Set<TEntity>()
// Only the soft delete and the tenant scope decide which rows name a key. Another filter, such as one that
// hides archived rows, hides live rows, and the sweep would delete their objects. The names come from the whole
// model, because a tenant filter through a navigation joins the owner with the filters of the owner.
string[] otherFilters = [.. column.EntityType.Model.GetEntityTypes()
.SelectMany(entityType => entityType.GetDeclaredQueryFilters())
.Select(filter => filter.Key)
.OfType<string>()
.Where(key => key is not (QueryFilterNames.SoftDelete or QueryFilterNames.Tenant))
.Distinct(StringComparer.Ordinal)];
return (dbContext, keys, cancellationToken) => (otherFilters.Length > 0
? dbContext.Set<TEntity>().IgnoreQueryFilters(otherFilters)
: dbContext.Set<TEntity>())
.TagWithOperationCallSite(operationName)
.Select(keyOf)
.Where(key => keys.Contains(key))
Expand Down
28 changes: 18 additions & 10 deletions FullstackTemplate.Server/Domain/ObjectDeletes/SweepObjects.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,26 +51,30 @@ protected override async Task RunAsync(SweepObjects job, JobContext context, Can

var activity = Activity.Current;
var (listed, kept, ofUnknownTenants, deleted) = (0, 0, 0, 0);
var (refusedCount, someRefused) = (0, new List<string>());
string? continuationToken = null;
do
{
var page = await ObjectDeletes.InAttemptTimeAsync(deleteOptions.Value.AttemptTimeout,
attempt => storage.ListPageAsync(StoredFile.TenantsPrefix, continuationToken, attempt), cancellationToken);
var decision = await DecideAsync(page.Objects, now, grace, cancellationToken);
if (decision.Orphans.Count > 0)
{
await ObjectDeletes.InAttemptTimeAsync(deleteOptions.Value.AttemptTimeout, async attempt =>
{
await storage.DeleteAsync(decision.Orphans, attempt);
return decision.Orphans.Count;
}, cancellationToken);
ObjectDeleteMetrics.Swept.Add(decision.Orphans.Count);
}
// A key that storage refuses to delete, as with Object Lock or a deny policy, does not stop the pages after it.
var refusedOfPage = decision.Orphans.Count > 0
? await ObjectDeletes.InAttemptTimeAsync(deleteOptions.Value.AttemptTimeout,
attempt => storage.DeleteAsync(decision.Orphans, attempt), cancellationToken)
: [];
if (refusedOfPage.Count > 0)
Logger.Here().Error(
"Storage refused the delete of {RefusedCount} objects that no row names, such as {Keys}. The sweep goes on to the next page",
refusedOfPage.Count, refusedOfPage.Take(10));
refusedCount += refusedOfPage.Count;
someRefused.AddRange(refusedOfPage.Take(10 - someRefused.Count));
ObjectDeleteMetrics.Swept.Add(decision.Orphans.Count - refusedOfPage.Count);

listed += page.Objects.Count;
kept += decision.Kept;
ofUnknownTenants += decision.OfUnknownTenants;
deleted += decision.Orphans.Count;
deleted += decision.Orphans.Count - refusedOfPage.Count;
activity?.SetTag("app.object_sweep.listed_count", listed);
activity?.SetTag("app.object_sweep.kept_count", kept);
activity?.SetTag("app.object_sweep.deleted_count", deleted);
Expand All @@ -84,6 +88,10 @@ await ObjectDeletes.InAttemptTimeAsync(deleteOptions.Value.AttemptTimeout, async
Logger.Here().Information(
"Swept the bucket: listed {ListedCount} objects, kept {KeptCount}, and deleted {DeletedCount} that no row names",
listed, kept, deleted);
// The run fails, so BackWave runs it again, and the delete of a key that is gone succeeds.
if (refusedCount > 0)
throw new InvalidOperationException(
$"Storage refused the delete of {refusedCount} objects that no row names, such as {string.Join(", ", someRefused)}.");
}

private async Task<SweepPage> DecideAsync(IReadOnlyList<StoredObject> objects, DateTimeOffset now, TimeSpan grace,
Expand Down
23 changes: 20 additions & 3 deletions FullstackTemplate.Server/Resources/Storage/ObjectStorage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,29 @@ public async Task DeleteAsync(string key, CancellationToken cancellationToken)
=> await s3.DeleteObjectAsync(new DeleteObjectRequest { BucketName = BucketName, Key = key }, cancellationToken);

/// <summary>
/// Deletes the objects, at most 1000. S3 gives success for a key that does not exist, so a second delete is a no-op.
/// Deletes the objects, at most 1000, and gives the keys that storage refused to delete, as with Object Lock or a
/// deny policy. The other keys of the batch go. S3 gives success for a key that does not exist, so a second delete
/// is a no-op.
/// </summary>
[SuppressMessage("ApiDesign", "RS0030:Do not use banned APIs",
Justification = "Reads the keys of a failed batch delete. Only AttachmentStorage.AddAsync puts.")]
public async Task<IReadOnlyList<string>> DeleteAsync(IReadOnlyCollection<string> keys, CancellationToken cancellationToken)
{
try
{
await DeleteBatchAsync(keys, cancellationToken);
return [];
}
catch (DeleteObjectsException exception)
{
return [.. exception.Response.DeleteErrors.Select(e => e.Key)];
}
}

/// <exception cref="DeleteObjectsException">A key failed to delete.</exception>
[SuppressMessage("ApiDesign", "RS0030:Do not use banned APIs",
Justification = "A delete of a batch of objects. Only AttachmentStorage.AddAsync puts.")]
public async Task DeleteAsync(IReadOnlyCollection<string> keys, CancellationToken cancellationToken)
private async Task DeleteBatchAsync(IReadOnlyCollection<string> keys, CancellationToken cancellationToken)
=> await s3.DeleteObjectsAsync(new DeleteObjectsRequest
{
BucketName = BucketName,
Expand All @@ -41,7 +58,7 @@ public async Task<int> DeleteUnderAsync(string prefix, CancellationToken cancell
{
var page = await ListPageAsync(prefix, continuationToken, cancellationToken);
if (page.Objects.Count > 0)
await DeleteAsync([.. page.Objects.Select(o => o.Key)], cancellationToken);
await DeleteBatchAsync([.. page.Objects.Select(o => o.Key)], cancellationToken);
deleted += page.Objects.Count;
continuationToken = page.NextToken;
} while (continuationToken is not null);
Expand Down
4 changes: 3 additions & 1 deletion docs/backend/attachments.md
Original file line number Diff line number Diff line change
Expand Up @@ -277,11 +277,13 @@ Each object under `tenants/` must be the `StoredFile` of a row. An add can leave

- BackWave runs the job each day at 03:00 UTC (`ObjectStorage:Sweep:Schedule`, a cron expression in UTC), on the queue `object-sweep`. Each start of the Server defines the schedule after the migrations. After a stop of all workers, the missed days give one run. A run does not start while the last run still runs.
- A run lists each object under `tenants/`, 1000 keys at a time. For each page, it loads the tenants of the keys and the keys that a live row names in a `StoredFile` column. Then it deletes each other object of the page. `StoredFileMapping.StorageKeyColumns` finds each such column in the EF model, also on a derived entity type and inside another value object, so a new stored file needs no change in the sweep. A collection of stored files stops the sweep, because it cannot read their keys.
- It keeps an object that is not older than the grace: `Attachments:AddTimeout` (5 minutes) plus `ObjectStorage:Sweep:Margin` (1 hour). An add stops its put and its save at `AddTimeout`. The margin covers a difference of the clocks of the Server and of storage, and a COMMIT that is still in flight when the add stops. It must be more than 15 minutes. The S3 client of the Server does not set its clock to the clock of storage, so storage refuses each call of a Server whose clock is more than 15 minutes off. Give each process the same `Attachments:AddTimeout`, because the process that runs the sweep takes the grace from its own settings.
- It keeps an object that is not older than the grace: `Attachments:AddTimeout` (5 minutes, at most 1 hour) plus `ObjectStorage:Sweep:Margin` (1 hour). An add stops its put and its save at `AddTimeout`. The margin covers a difference of the clocks of the Server and of storage, and a COMMIT that is still in flight when the add stops. It must be more than 15 minutes. The S3 client of the Server does not set its clock to the clock of storage, so storage refuses each call of a Server whose clock is more than 15 minutes off. Give each process the same `Attachments:AddTimeout`, because the process that runs the sweep takes the grace from its own settings.
- A soft-deleted row does not name its key. So the sweep also deletes the object of a deleted row whose job did not delete it, for example a dead job, and the object of a deleted row that had no job. Only the `File` of an `IAttachment` gets a job.
- Only the soft delete and the tenant scope decide which rows name a key. The look-up ignores each other named query filter of the model, also one on the owner of a row, such as one that hides archived rows, because a hidden row is still live and its object must stay.
- It keeps an object whose key names no tenant of the database, and writes the Warning log `Kept {ObjectCount} objects whose keys name no tenant of this database`. A deleted tenant is a tenant of the database. Give each database its own bucket: a copy of the database that uses the same bucket, such as a staging copy, deletes each object of a row that the copy does not have.
- It does not run when the database has a migration that the Server does not know, for example while an older Server runs during a deploy or after a rollback. An older Server does not see the storage key columns of a newer one. It then writes the Warning log `Skipped the sweep of the bucket` with the names of the migrations.
- Each run is a trace of its own. Its process span has the tags `app.object_sweep.listed_count`, `app.object_sweep.kept_count`, and `app.object_sweep.deleted_count`. The run ends with the Information log `Swept the bucket`, and the metric `app.objects.swept` counts the deleted objects.
- A key that storage refuses to delete, as with Object Lock or a deny policy, does not stop the run. The run writes the Error log `Storage refused the delete of {RefusedCount} objects`, goes on to the next page, and fails at the end, so BackWave runs it again.
- One call to storage stops after `ObjectStorage:Deletes:AttemptTimeout` (1 minute). A failed run runs again with the policy of its worker group, and a run that deleted some objects does no harm when it runs again.

Do not put an object under `tenants/` that no `StoredFile` of a row names, because the sweep deletes it. `AttachmentStorage.AddAsync` is the one put of the Server. The build bans each call to a member of `ObjectWriter` or of a type in the `Amazon.S3` namespace in each other place (RS0030).
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
namespace FullstackTemplate.IntegrationTests.Examples.Workshops;

using FullstackTemplate.IntegrationTests.ObjectDeletes;
using FullstackTemplate.Server.Databases;
using FullstackTemplate.Server.Domain.Users;
using FullstackTemplate.Server.Examples.Workshops;
using FullstackTemplate.Server.Examples.Workshops.Features;
using FullstackTemplate.SharedTestHelpers.EntityGraphs;
using FullstackTemplate.SharedTestHelpers.Examples.EntityGraphs;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;

/// <summary>The sweep of the bucket reads each storage key column, here the one of the workshop attachments.</summary>
Expand Down Expand Up @@ -51,5 +56,37 @@ public async Task the_object_of_a_deleted_attachment_goes_when_its_delete_job_di
(await bucket.KeysAsync()).ShouldBeEmpty();
}

[Test]
public async Task the_object_of_a_live_attachment_that_a_query_filter_of_the_app_hides_stays()
{
// Arrange
await using var bucket = await SweepBucket.CreateAsync();
await new TestingServiceScope().StartGraph(out _)
.AddTenant(out var tenant)
.Under(tenant).AddVenue(out _).AddWorkshop(out _).AddWorkshopAttachment(out var attachment)
.BuildAsync();
var stored = await bucket.PutAsync(attachment.File.StorageKey);

// Act
await bucket.SweepAsync(stored.LastModified + SweepBucket.Grace + TimeSpan.FromSeconds(1), configure: services =>
services.ConfigureDbContext<AppDbContext>(options => options.ReplaceService<IModelCustomizer, HidingAttachmentsCustomizer>()));

// Assert
(await bucket.KeysAsync()).ShouldBe([stored.Key], "A live row names the object, though a filter of the app hides the row.");
}

private static DateTimeOffset Latest(DateTimeOffset first, DateTimeOffset second) => first > second ? first : second;

/// <summary>
/// Adds a query filter to the model, as an app does that hides archived rows. A customizer keeps the type of the
/// context, so the sweep still finds the migrations of the Server.
/// </summary>
private sealed class HidingAttachmentsCustomizer(ModelCustomizerDependencies dependencies) : RelationalModelCustomizer(dependencies)
{
public override void Customize(ModelBuilder modelBuilder, DbContext context)
{
base.Customize(modelBuilder, context);
modelBuilder.Entity<WorkshopAttachment>().HasQueryFilter("Archived", _ => false);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,20 +44,29 @@ public ServiceProvider Server(string? connectionString = null, Action<IServiceCo
configure?.Invoke(services);
}, connectionString));

/// <summary>Runs one sweep on a Server of this bucket whose clock reads <paramref name="now"/>.</summary>
public async Task SweepAsync(DateTimeOffset now, string? connectionString = null)
/// <summary>Runs one sweep on a Server of this bucket whose clock reads <paramref name="now"/>, and checks that it succeeded.</summary>
public async Task SweepAsync(DateTimeOffset now, string? connectionString = null, Action<IServiceCollection>? configure = null)
{
var (state, failures) = await RunSweepAsync(now, connectionString, configure);
state.ShouldBe(JobState.Succeeded, string.Join('\n', failures));
}

/// <summary>Runs one attempt of the sweep on a Server of this bucket whose clock reads <paramref name="now"/>.</summary>
public async Task<(JobState State, List<string> Failures)> RunSweepAsync(DateTimeOffset now, string? connectionString = null,
Action<IServiceCollection>? configure = null)
{
var sweeper = Track(TestFixture.BuildServiceProvider(services =>
{
services.AddSingleton(Options.Create(new ObjectStorageOptions { BucketName = Name }));
services.Replace(ServiceDescriptor.Singleton<TimeProvider>(new FixedClock(now)));
configure?.Invoke(services);
}, connectionString));
await using var harness = new JobHarness(sweeper, new RetryPolicy { MaxAttempts = 1 });

var jobId = await harness.EnqueueAsync(new SweepObjects());
await harness.RunDueAsync();

(await harness.JobAsync(jobId)).State.ShouldBe(JobState.Succeeded, string.Join('\n', await harness.FailuresOfAsync(jobId)));
return ((await harness.JobAsync(jobId)).State, await harness.FailuresOfAsync(jobId));
}

public async Task<StoredObject> PutAsync(string key)
Expand Down
Loading
Loading