Skip to content
Merged
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
2 changes: 1 addition & 1 deletion .agents/skills/object-storage-lifecycle/SKILL.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
name: object-storage-lifecycle
description: Model-checks the life of an attachment row, its object in the bucket, the BackWave jobs that delete objects, and the sweep of the objects that no row names, with TLA+ and TLC. Use when you change AttachmentStorage, an add or delete of an attachment, DeleteTenant, RootLock, AppDbContext.PrepareWrite, ObjectDeletes, the DeleteObject, DeleteTenantObjects, or SweepObjects job, ObjectDeleteOptions, ObjectSweepOptions, AttachmentOptions, or ObjectStorage, or when you ask whether an object can outlive its row or a row can lose its object.
description: Model-checks the life of an attachment row, its object in the bucket, the BackWave jobs that delete objects, and the sweep of the objects that no row names, with TLA+ and TLC. Use when you change AttachmentStorage, an add or delete of an attachment, DeleteTenant, RootLock, AppDbContext.PrepareWrite, ObjectDeletes, the DeleteObject, DeleteTenantObjects, or SweepObjects job, ObjectDeleteOptions, ObjectSweepOptions, AttachmentOptions, ObjectStorage, or ObjectWriter, or when you ask whether an object can outlive its row or a row can lose its object.
---

# Object storage lifecycle
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ StartAdd(a) ==
/\ apc' = [apc EXCEPT ![a] = "put"]
/\ UNCHANGED <<tenant, row, obj, shared, td, req, runVars, sweepVars, crashes>>

\* AddAsync: storage.PutAsync. A put that throws can still have stored the object.
\* AddAsync: writer.PutAsync. A put that throws can still have stored the object.
Put(a) ==
/\ apc[a] = "put"
/\ \/ /\ obj' = [obj EXCEPT ![a] = TRUE]
Expand Down
5 changes: 5 additions & 0 deletions FullstackTemplate.Server/BannedSymbols.txt
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,8 @@ M:System.Type.GetProperties(System.Reflection.BindingFlags);Check docs/backend/s
// Resources/Jobs/JobWriter.cs writes the queued jobs of each save. Domain/ObjectDeletes/ObjectSweepSchedule.cs defines the
// one schedule. Only these two files suppress this ban.
T:BackWave.BackWaveClient;Queue a job with dbContext.QueueJob, so that it commits with the save.
// The sweep of the bucket deletes an object with no row after Attachments:AddTimeout and a margin, and only
// AttachmentStorage.AddAsync saves the row within that time. So AddAsync is the one put of the Server. AddAsync, the S3
// members of ObjectStorage, ObjectWriter, and ObjectStorageRegistration.AddObjectStorage suppress these bans.
T:FullstackTemplate.Server.Resources.Storage.ObjectWriter;Put an object with AttachmentStorage.AddAsync, so that the sweep of the bucket keeps it until its row is saved.
N:Amazon.S3;The S3 client goes around ObjectStorage and AttachmentStorage. Put an object with AttachmentStorage.AddAsync. List, delete, and sign with ObjectStorage.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
namespace FullstackTemplate.Server.Domain.Attachments;

using System.Diagnostics.CodeAnalysis;
using Databases;
using Microsoft.Extensions.Options;
using ObjectDeletes;
Expand All @@ -10,7 +11,7 @@ namespace FullstackTemplate.Server.Domain.Attachments;
/// download, so the object goes first on an add and last on a delete. An object with no row costs only its storage, and
/// the sweep of the bucket deletes it.
/// </summary>
public sealed class AttachmentStorage(AppDbContext dbContext, ObjectStorage storage, IOptions<AttachmentOptions> options)
public sealed class AttachmentStorage(AppDbContext dbContext, ObjectWriter writer, IOptions<AttachmentOptions> options)
{
/// <summary>
/// Puts the bytes of a new attachment in storage, then runs the save of its row. When the put or the save throws,
Expand All @@ -23,6 +24,8 @@ public sealed class AttachmentStorage(AppDbContext dbContext, ObjectStorage stor
/// the save can run in a lock that runs its work again.</param>
/// <param name="cancellationToken">Stops the put and the save.</param>
/// <exception cref="TimeoutException">The put and the save took longer than <see cref="AttachmentOptions.AddTimeout"/>.</exception>
[SuppressMessage("ApiDesign", "RS0030:Do not use banned APIs",
Justification = "AddAsync is the one put of the Server. It ends the put and the save within AddTimeout.")]
public async Task AddAsync<TAttachment>(TAttachment attachment, ReceivedFile file, Func<CancellationToken, Task> saveRow,
CancellationToken cancellationToken)
where TAttachment : BaseEntity, IAttachment
Expand All @@ -35,7 +38,7 @@ public async Task AddAsync<TAttachment>(TAttachment attachment, ReceivedFile fil
add.CancelAfter(addTimeout);
try
{
await storage.PutAsync(attachment.File.StorageKey, file.Content, attachment.File.MediaType, add.Token);
await writer.PutAsync(attachment.File.StorageKey, file.Content, attachment.File.MediaType, add.Token);
await saveRow(add.Token);
}
catch (OperationCanceledException exception)
Expand Down
22 changes: 10 additions & 12 deletions FullstackTemplate.Server/Resources/Storage/ObjectStorage.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
namespace FullstackTemplate.Server.Resources.Storage;

using System.Diagnostics.CodeAnalysis;
using Amazon.S3;
using Amazon.S3.Model;
using Microsoft.Extensions.Options;
Expand All @@ -8,25 +9,18 @@ public sealed class ObjectStorage(IAmazonS3 s3, IOptions<ObjectStorageOptions> o
{
private string BucketName => options.Value.BucketName;

public async Task PutAsync(string key, Stream content, string contentType, CancellationToken cancellationToken)
=> await s3.PutObjectAsync(new PutObjectRequest
{
BucketName = BucketName,
Key = key,
InputStream = content,
ContentType = contentType,
// The caller owns the stream
AutoCloseStream = false,
}, cancellationToken);

/// <summary>Deletes the object. 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 = "A delete of one object. Only AttachmentStorage.AddAsync puts.")]
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.
/// </summary>
/// <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)
=> await s3.DeleteObjectsAsync(new DeleteObjectsRequest
{
Expand All @@ -37,7 +31,7 @@ public async Task DeleteAsync(IReadOnlyCollection<string> keys, CancellationToke

/// <summary>
/// Deletes each object whose key starts with the prefix, one page of keys at a time, and gives the number of keys.
/// A key that fails to delete throws a <see cref="DeleteObjectsException"/>, and the keys of the pages after it stay.
/// A key that fails to delete throws a <c>DeleteObjectsException</c>, and the keys of the pages after it stay.
/// </summary>
public async Task<int> DeleteUnderAsync(string prefix, CancellationToken cancellationToken)
{
Expand All @@ -59,6 +53,8 @@ public async Task<int> DeleteUnderAsync(string prefix, CancellationToken cancell
/// One page of the objects whose key starts with the prefix, at most 1000, in the order of their keys. Give the
/// <see cref="ObjectPage.NextToken"/> of a page to get the page after it.
/// </summary>
[SuppressMessage("ApiDesign", "RS0030:Do not use banned APIs",
Justification = "A list of one page of keys. Only AttachmentStorage.AddAsync puts.")]
public async Task<ObjectPage> ListPageAsync(string prefix, string? continuationToken, CancellationToken cancellationToken)
{
var page = await s3.ListObjectsV2Async(new ListObjectsV2Request
Expand All @@ -77,6 +73,8 @@ public async Task<ObjectPage> ListPageAsync(string prefix, string? continuationT
/// Signs a GET URL. The signature is local work with no call to S3, so the URL does not prove that the object
/// exists. Anyone with the URL can read the object until it expires, so sign only after an access check.
/// </summary>
[SuppressMessage("ApiDesign", "RS0030:Do not use banned APIs",
Justification = "A signed GET URL. Only AttachmentStorage.AddAsync puts.")]
public Task<string> GetPresignedUrlAsync(PresignedGet get)
{
var request = new GetPreSignedUrlRequest
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
namespace FullstackTemplate.Server.Resources.Storage;

using System.Diagnostics.CodeAnalysis;
using Amazon.S3;

public static class ObjectStorageRegistration
Expand All @@ -9,10 +10,13 @@ public static class ObjectStorageRegistration
private const string RegionKey = "AWS_DEFAULT_REGION";

/// <summary>
/// Adds <see cref="ObjectStorage"/>. With no endpoint, the client calls S3 of AWS, and the SDK finds the region
/// and the credentials in its default chain. An endpoint, such as Floci in a local run, gets path-style URLs, so
/// that the host of a URL is the endpoint host and not a subdomain with the bucket name.
/// Adds the S3 client, <see cref="ObjectStorage"/>, and <see cref="ObjectWriter"/>. With no endpoint, the client
/// calls S3 of AWS, and the SDK finds the region and the credentials in its default chain. An endpoint, such as
/// Floci in a local run, gets path-style URLs, so that the host of a URL is the endpoint host and not a subdomain
/// with the bucket name.
/// </summary>
[SuppressMessage("ApiDesign", "RS0030:Do not use banned APIs",
Justification = "The registration makes the one S3 client of ObjectStorage and ObjectWriter.")]
public static void AddObjectStorage(this WebApplicationBuilder builder)
{
builder.Services.AddOptions<ObjectStorageOptions>()
Expand All @@ -35,5 +39,6 @@ public static void AddObjectStorage(this WebApplicationBuilder builder)
return new AmazonS3Client(config);
});
builder.Services.AddSingleton<ObjectStorage>();
builder.Services.AddSingleton<ObjectWriter>();
}
}
22 changes: 22 additions & 0 deletions FullstackTemplate.Server/Resources/Storage/ObjectWriter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
namespace FullstackTemplate.Server.Resources.Storage;

using System.Diagnostics.CodeAnalysis;
using Amazon.S3;
using Amazon.S3.Model;
using Microsoft.Extensions.Options;

[SuppressMessage("ApiDesign", "RS0030:Do not use banned APIs",
Justification = "ObjectWriter owns the put of the S3 client.")]
public sealed class ObjectWriter(IAmazonS3 s3, IOptions<ObjectStorageOptions> options)
{
public async Task PutAsync(string key, Stream content, string contentType, CancellationToken cancellationToken)
=> await s3.PutObjectAsync(new PutObjectRequest
{
BucketName = options.Value.BucketName,
Key = key,
InputStream = content,
ContentType = contentType,
// The caller owns the stream
AutoCloseStream = false,
}, cancellationToken);
}
2 changes: 1 addition & 1 deletion docs/backend.md
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ The server applies migrations at startup, with a Postgres advisory lock. Under t

## Object storage

The Server keeps the bytes of files in one S3 bucket. The database keeps the metadata of each file and the key of its object. `Resources/Storage/ObjectStorage.cs` puts an object, lists the objects under a prefix, deletes objects or each object under a prefix, and signs a URL that reads an object. `Resources/Storage/ObjectStorageRegistration.cs` adds the S3 client.
The Server keeps the bytes of files in one S3 bucket. The database keeps the metadata of each file and the key of its object. `Resources/Storage/ObjectStorage.cs` lists the objects under a prefix, deletes objects or each object under a prefix, and signs a URL that reads an object. `Resources/Storage/ObjectWriter.cs` puts an object. `Resources/Storage/ObjectStorageRegistration.cs` adds the S3 client. Only `AttachmentStorage.AddAsync` puts an object. The build bans each call to a member of `ObjectWriter` or of a type in the `Amazon.S3` namespace in each other place (RS0030).

| Where | Storage |
|-------|---------|
Expand Down
2 changes: 1 addition & 1 deletion docs/backend/attachments.md
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ Each object under `tenants/` must be the `StoredFile` of a row. An add can leave
- 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.
- 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. Put other files under another prefix.
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).

## Tenant isolation

Expand Down
8 changes: 8 additions & 0 deletions docs/template-updates.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,14 @@ A recurring job now deletes each object in storage that no live row names (see [
- The sweep does not run while the database has a migration that the Server does not know. If the app deleted a migration that its database ran, for example with `scripts/remove-examples.cs`, delete the row of that migration from `__EFMigrationsHistory`. The Warning log `Skipped the sweep of the bucket` names each such migration.
- `AttachmentStorage.AddAsync` now gives the save of the row a token, and stops the put and the save after `Attachments:AddTimeout`. The build fails at each add of an attachment entity of the app. Change `async () =>` to `async addToken =>`, and give `addToken` to `RootLock.Tenant.RunSharedAsync` in place of the token of the request.

### The update that bans a put outside AttachmentStorage

`AttachmentStorage.AddAsync` is now the one put of the Server, because the sweep of the bucket can delete the object of a put on another path before its row is saved (see [attachments.md](backend/attachments.md#the-sweep-of-the-bucket)). `ObjectStorage.PutAsync` is gone, and `ObjectWriter` has the put.

- The build fails (RS0030) at each call to a member of `ObjectWriter` or of a type in the `Amazon.S3` namespace outside `AttachmentStorage.AddAsync`, the S3 members of `ObjectStorage`, `ObjectWriter`, and `ObjectStorageRegistration.AddObjectStorage`.
- Give the put of each attachment entity of the app to `AttachmentStorage.AddAsync`.
- For a file that is not an attachment, such as an export, put it under a prefix other than `tenants/`. Suppress RS0030 on the method that puts it, with a justification, and add the file to the list of `BannedApiSuppressionTests`.

## Keep the next update small

- When you find a fault in the template, report it as an issue of the template, and get the fix with the next update. A fix that you copy by hand gives a conflict when the fix of the template comes.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@ public async Task a_delete_under_a_prefix_deletes_each_object_on_each_page_and_k
var prefix = $"tenants/{Guid.NewGuid():N}/";
var outside = $"tenants/{Guid.NewGuid():N}/kept";
var keys = Enumerable.Range(0, 1001).Select(i => $"{prefix}files/{i}").Append(outside).ToList();
var storage = new TestingServiceScope().GetService<ObjectStorage>();
var scope = new TestingServiceScope();
var storage = scope.GetService<ObjectStorage>();
var writer = scope.GetService<ObjectWriter>();
await Parallel.ForEachAsync(keys, new ParallelOptions { MaxDegreeOfParallelism = 16 }, async (key, ct) =>
{
using var content = new MemoryStream([1]);
await storage.PutAsync(key, content, "application/octet-stream", ct);
await writer.PutAsync(key, content, "application/octet-stream", ct);
});
(await FirstPageUnderAsync(prefix)).IsTruncated.ShouldBe(true);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,17 @@ public class BannedApiSuppressionTests
"FullstackTemplate.Server/Databases/ObjectDeleteRequestsDrain.cs",
"FullstackTemplate.Server/Databases/PostgresCopy.cs",
"FullstackTemplate.Server/Databases/RootLock.cs",
"FullstackTemplate.Server/Domain/Attachments/AttachmentStorage.cs",
"FullstackTemplate.Server/Domain/DPoPProofs/Features/DeleteExpiredDPoPProofs/DeleteExpiredDPoPProofs.cs",
"FullstackTemplate.Server/Domain/DPoPProofs/Features/RegisterDPoPProof/RegisterDPoPProof.cs",
"FullstackTemplate.Server/Domain/ObjectDeletes/ObjectSweepSchedule.cs",
"FullstackTemplate.Server/Databases/Auditing/AuditVocabulary.cs",
"FullstackTemplate.Server/Resources/Entrypoints/Http/EndpointDiscovery.cs",
"FullstackTemplate.Server/Resources/Jobs/JobWriter.cs",
"FullstackTemplate.Server/Resources/RequestValidationBehavior.cs",
"FullstackTemplate.Server/Resources/Storage/ObjectStorage.cs",
"FullstackTemplate.Server/Resources/Storage/ObjectStorageRegistration.cs",
"FullstackTemplate.Server/Resources/Storage/ObjectWriter.cs",
];

private static readonly string[] SettingsExtensions = [".cs", ".csproj", ".props", ".editorconfig", ".globalconfig"];
Expand Down
Loading