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: 2 additions & 0 deletions docs/error-ingestion-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ When `BodyStoredExternally` is true the external copy is authoritative and `Body
search aid only; it must never be served as the body. `BodySize` is always the original
size. External writes happen before the row that points at them is committed.

Error ingestion resolves the unique message id to a GUID once, before the external write. It parses a valid GUID in `ServiceControl.Retry.UniqueMessageId` and converts any other value with `DeterministicGuid.MakeId(value)`, matching Audit ingestion. Without that header, it derives the GUID from the message id and processing endpoint. The external body id uses the canonical string representation of the database `UniqueMessageId`, so a malformed header value never becomes a file path.

### Groups, endpoints, retention

- **Failure groups** live in `FailedMessageGroups`, an association table. A message's group rows
Expand Down
2 changes: 1 addition & 1 deletion docs/message-body-storage.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Ingestion writes external bodies before the batch transaction that inserts the r

Audit stores a body through `IAuditBodyStoragePersistence` under the UTC ingestion hour of its batch and the unique message id: `yyyyMMddHH/{unique message id}`. The file system store writes `{StoragePath}/yyyyMMddHH/{unique message id}.body`, the Azure Blob store uses the blob name `yyyyMMddHH/{unique message id}`, and the S3 store prepends its key prefix. Callers pass the hour explicitly and the stores do not parse it from the id, so reads use the `CreatedOn` of the row. Storage keeps the first write for an hour and id and ignores later writes.

The body URL keeps the audit body id, `yyyyMMddHH-{unique message id}`, which routes the request to the row. The Error (primary) persisters use `IBodyStoragePersistence` with the body id alone; their file system layout remains `{StoragePath}/{body id}.body`.
The body URL keeps the audit body id, `yyyyMMddHH-{unique message id}`, which routes the request to the row. The Error (primary) persisters use `IBodyStoragePersistence` with the body id alone; their file system layout remains `{StoragePath}/{body id}.body`. Both file system stores validate body ids with `Guid.TryParse` before file system access and throw `ArgumentException` for invalid ids. Audit requires a GUID. Error accepts a GUID or `failedimport-{guid}`, the id of a failed import body.

Reading a body streams it from storage with the stored content type, size, and a version derived from the row. A body missing from storage answers 204.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ public class AuditFileSystemBodyStorage(FileSystemBodyStorageSettings settings)

public async Task WriteBody(string bodyId, DateTime createdOn, ReadOnlyMemory<byte> body, string contentType, CancellationToken cancellationToken = default)
{
Directory.CreateDirectory(HourDirectory(createdOn));

var filePath = GetBodyFilePath(createdOn, bodyId);

Directory.CreateDirectory(HourDirectory(createdOn));

if (File.Exists(filePath))
{
return;
Expand Down Expand Up @@ -163,7 +163,15 @@ public async Task DeleteBodiesForDay(DateTime day, CancellationToken cancellatio

string HourDirectory(DateTime hour) => Path.Combine(StoragePath, AuditBodyStorageKey.HourPrefix(hour));

string GetBodyFilePath(DateTime createdOn, string bodyId) => Path.Combine(StoragePath, $"{AuditBodyStorageKey.For(createdOn, bodyId)}.body");
string GetBodyFilePath(DateTime createdOn, string bodyId)
{
if (!Guid.TryParse(bodyId, out _))
{
throw new ArgumentException("The body id must be a GUID.", nameof(bodyId));
}

return Path.Combine(StoragePath, $"{AuditBodyStorageKey.For(createdOn, bodyId)}.body");
}

static void TryDelete(string filePath)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,30 @@ namespace ServiceControl.Audit.Persistence.Tests.EFCore;
[TestFixture]
class AuditFileSystemBodyStorageTests
{
const string BodyId = "6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10";
const string BodyA = "a0000000-0000-4000-8000-00000000000a";
const string BodyB = "b0000000-0000-4000-8000-00000000000b";
const string BodyC = "c0000000-0000-4000-8000-00000000000c";
const string BodyD = "d0000000-0000-4000-8000-00000000000d";

string tempDir;
string outsideDir;
AuditFileSystemBodyStorage store;

[SetUp]
public void SetUp()
{
tempDir = Directory.CreateTempSubdirectory("sc-body-tests-").FullName;
outsideDir = Directory.CreateTempSubdirectory("sc-body-outside-").FullName;
store = new AuditFileSystemBodyStorage(new FileSystemBodyStorageSettings { StoragePath = tempDir, MinCompressionSize = 64 });
}

[TearDown]
public void TearDown() => Directory.Delete(tempDir, recursive: true);
public void TearDown()
{
Directory.Delete(tempDir, recursive: true);
Directory.Delete(outsideDir, recursive: true);
}

static readonly DateTime Hour10 = new(2026, 10, 20, 10, 0, 0, DateTimeKind.Utc);
static readonly DateTime Hour11 = Hour10.AddHours(1);
Expand All @@ -34,9 +46,9 @@ public void SetUp()
public async Task Round_trips_compressed_and_uncompressed_bodies(int bodyLength)
{
var body = Encoding.UTF8.GetBytes(new string('a', bodyLength));
await store.WriteBody("body-1", Hour10, body, "application/json");
await store.WriteBody(BodyId, Hour10, body, "application/json");

var result = await store.ReadBody("body-1", Hour10);
var result = await store.ReadBody(BodyId, Hour10);

Assert.That(result, Is.Not.Null);
using (result.Stream)
Expand All @@ -52,24 +64,24 @@ public async Task Round_trips_compressed_and_uncompressed_bodies(int bodyLength)
}

[Test]
public async Task Body_is_stored_in_the_directory_of_its_explicit_hour_whatever_the_id()
public async Task Body_is_stored_in_the_directory_of_its_explicit_hour()
{
await store.WriteBody("opaque", Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain");
await store.WriteBody(BodyId, Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain");

Assert.That(Relative(), Is.EqualTo(new[] { Path.Combine("2026102010", "opaque.body") }));
var result = await store.ReadBody("opaque", Hour10);
Assert.That(Relative(), Is.EqualTo(new[] { Path.Combine("2026102010", $"{BodyId}.body") }));
var result = await store.ReadBody(BodyId, Hour10);
Assert.That(result, Is.Not.Null);
result.Stream.Dispose();
}

[Test]
public async Task Bodies_with_the_same_id_in_different_hours_are_distinct()
{
await store.WriteBody("same", Hour10, Encoding.UTF8.GetBytes("ten"), "text/plain");
await store.WriteBody("same", Hour11, Encoding.UTF8.GetBytes("eleven"), "text/plain");
await store.WriteBody(BodyId, Hour10, Encoding.UTF8.GetBytes("ten"), "text/plain");
await store.WriteBody(BodyId, Hour11, Encoding.UTF8.GetBytes("eleven"), "text/plain");

using var ten = (await store.ReadBody("same", Hour10)).Stream;
using var eleven = (await store.ReadBody("same", Hour11)).Stream;
using var ten = (await store.ReadBody(BodyId, Hour10)).Stream;
using var eleven = (await store.ReadBody(BodyId, Hour11)).Stream;

Assert.Multiple(() =>
{
Expand All @@ -81,18 +93,18 @@ public async Task Bodies_with_the_same_id_in_different_hours_are_distinct()
[Test]
public async Task Read_for_another_hour_finds_nothing()
{
await store.WriteBody("a", Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain");
await store.WriteBody(BodyA, Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain");

Assert.That(await store.ReadBody("a", Hour11), Is.Null);
Assert.That(await store.ReadBody("a", Hour10.AddDays(-1)), Is.Null);
Assert.That(await store.ReadBody(BodyA, Hour11), Is.Null);
Assert.That(await store.ReadBody(BodyA, Hour10.AddDays(-1)), Is.Null);
}

[Test]
public async Task Read_with_an_unspecified_kind_finds_the_body_of_the_same_clock_hour()
{
await store.WriteBody("a", Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain");
await store.WriteBody(BodyA, Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain");

var result = await store.ReadBody("a", DateTime.SpecifyKind(Hour10, DateTimeKind.Unspecified));
var result = await store.ReadBody(BodyA, DateTime.SpecifyKind(Hour10, DateTimeKind.Unspecified));

Assert.That(result, Is.Not.Null);
result.Stream.Dispose();
Expand All @@ -101,10 +113,10 @@ public async Task Read_with_an_unspecified_kind_finds_the_body_of_the_same_clock
[Test]
public async Task Rewriting_a_body_keeps_the_first_write()
{
await store.WriteBody("a", Hour10, Encoding.UTF8.GetBytes("original"), "text/plain");
await store.WriteBody("a", Hour10, Encoding.UTF8.GetBytes("different"), "text/plain");
await store.WriteBody(BodyA, Hour10, Encoding.UTF8.GetBytes("original"), "text/plain");
await store.WriteBody(BodyA, Hour10, Encoding.UTF8.GetBytes("different"), "text/plain");

using var result = (await store.ReadBody("a", Hour10)).Stream;
using var result = (await store.ReadBody(BodyA, Hour10)).Stream;

Assert.That(ReadAll(result), Is.EqualTo(Encoding.UTF8.GetBytes("original")));
}
Expand All @@ -113,28 +125,28 @@ public async Task Rewriting_a_body_keeps_the_first_write()
public async Task Delete_for_hour_removes_only_that_hour()
{
var body = Encoding.UTF8.GetBytes("payload");
await store.WriteBody("a", Hour10, body, "text/plain");
await store.WriteBody("b", Hour10, body, "text/plain");
await store.WriteBody("a", Hour11, body, "text/plain");
await store.WriteBody(BodyA, Hour10, body, "text/plain");
await store.WriteBody(BodyB, Hour10, body, "text/plain");
await store.WriteBody(BodyA, Hour11, body, "text/plain");
var unrelated = Path.Combine(tempDir, "flat.body");
await File.WriteAllTextAsync(unrelated, "keep");

await store.DeleteBodiesForHour(Hour10);

Assert.Multiple(() =>
{
Assert.That(Relative(), Is.EquivalentTo(new[] { Path.Combine("2026102011", "a.body"), "flat.body" }));
Assert.That(Relative(), Is.EquivalentTo(new[] { Path.Combine("2026102011", $"{BodyA}.body"), "flat.body" }));
Assert.That(Directory.Exists(Path.Combine(tempDir, "2026102010")), Is.False);
});
}

[Test]
public async Task Delete_for_hour_also_removes_temp_files_in_that_hour_only()
{
await store.WriteBody("a", Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain");
await store.WriteBody("a", Hour11, Encoding.UTF8.GetBytes("payload"), "text/plain");
await File.WriteAllTextAsync(Path.Combine(tempDir, "2026102010", "a.body.abc.tmp"), "in progress");
var otherTemp = Path.Combine(tempDir, "2026102011", "a.body.abc.tmp");
await store.WriteBody(BodyA, Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain");
await store.WriteBody(BodyA, Hour11, Encoding.UTF8.GetBytes("payload"), "text/plain");
await File.WriteAllTextAsync(Path.Combine(tempDir, "2026102010", $"{BodyA}.body.abc.tmp"), "in progress");
var otherTemp = Path.Combine(tempDir, "2026102011", $"{BodyA}.body.abc.tmp");
await File.WriteAllTextAsync(otherTemp, "in progress");
var rootFile = Path.Combine(tempDir, "unrelated.txt");
await File.WriteAllTextAsync(rootFile, "keep");
Expand All @@ -153,17 +165,17 @@ public async Task Delete_for_hour_also_removes_temp_files_in_that_hour_only()
public async Task Delete_for_day_removes_every_hour_of_that_day_and_no_other()
{
var body = Encoding.UTF8.GetBytes("payload");
await store.WriteBody("a", Hour10.Date, body, "text/plain");
await store.WriteBody("b", Hour10.Date.AddHours(23), body, "text/plain");
await store.WriteBody("c", Hour10.Date.AddDays(1), body, "text/plain");
await store.WriteBody("d", Hour10.Date.AddHours(-1), body, "text/plain");
await store.WriteBody(BodyA, Hour10.Date, body, "text/plain");
await store.WriteBody(BodyB, Hour10.Date.AddHours(23), body, "text/plain");
await store.WriteBody(BodyC, Hour10.Date.AddDays(1), body, "text/plain");
await store.WriteBody(BodyD, Hour10.Date.AddHours(-1), body, "text/plain");
Directory.CreateDirectory(Path.Combine(tempDir, "20261020-unrelated"));

await store.DeleteBodiesForDay(Hour10);

Assert.Multiple(() =>
{
Assert.That(Relative(), Is.EquivalentTo(new[] { Path.Combine("2026102100", "c.body"), Path.Combine("2026101923", "d.body") }));
Assert.That(Relative(), Is.EquivalentTo(new[] { Path.Combine("2026102100", $"{BodyC}.body"), Path.Combine("2026101923", $"{BodyD}.body") }));
Assert.That(Directory.Exists(Path.Combine(tempDir, "20261020-unrelated")), Is.True);
});
}
Expand All @@ -178,7 +190,7 @@ public void Delete_succeeds_when_nothing_is_stored()
[Test]
public async Task Delete_honors_cancellation()
{
await store.WriteBody("a", Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain");
await store.WriteBody(BodyA, Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain");
using var cts = new CancellationTokenSource();
await cts.CancelAsync();

Expand All @@ -187,6 +199,40 @@ public async Task Delete_honors_cancellation()
Assert.That(Relative(), Has.Length.EqualTo(1));
}

[TestCase(null)]
[TestCase("")]
[TestCase("body-1")]
[TestCase("../6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10")]
[TestCase("..\\6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10")]
[TestCase("/etc/6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10")]
[TestCase("C:\\temp\\6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10")]
[TestCase("failedimport-6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10")]
[TestCase("outside-relative")]
[TestCase("outside-rooted")]
public async Task Invalid_body_ids_are_rejected_without_touching_the_file_system(string bodyId)
{
var outsideFile = Path.Combine(outsideDir, "target.body");
await File.WriteAllTextAsync(outsideFile, "keep");
bodyId = bodyId switch
{
"outside-relative" => Path.GetRelativePath(Path.Combine(tempDir, "2026102010"), Path.Combine(outsideDir, "target")),
"outside-rooted" => Path.Combine(outsideDir, "target"),
_ => bodyId
};

var write = Assert.ThrowsAsync<ArgumentException>(() => store.WriteBody(bodyId, Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain"));
var read = Assert.ThrowsAsync<ArgumentException>(() => store.ReadBody(bodyId, Hour10));

Assert.Multiple(() =>
{
Assert.That(write.ParamName, Is.EqualTo("bodyId"));
Assert.That(read.ParamName, Is.EqualTo("bodyId"));
Assert.That(Directory.GetFileSystemEntries(tempDir), Is.Empty);
Assert.That(Directory.GetFileSystemEntries(outsideDir), Is.EqualTo(new[] { outsideFile }));
Assert.That(File.ReadAllText(outsideFile), Is.EqualTo("keep"));
});
}

string[] Relative() => Directory.GetFiles(tempDir, "*", SearchOption.AllDirectories).Select(f => Path.GetRelativePath(tempDir, f)).ToArray();

static byte[] ReadAll(Stream stream)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,20 @@ public Task DeleteBodyIfExists(string bodyId, CancellationToken cancellationToke
return Task.CompletedTask;
}

string GetBodyFilePath(string bodyId) => Path.Combine(StoragePath, $"{bodyId}.body");
string GetBodyFilePath(string bodyId)
{
const string FailedImportPrefix = "failedimport-";
var guidText = bodyId is not null && bodyId.StartsWith(FailedImportPrefix, StringComparison.Ordinal)
? bodyId[FailedImportPrefix.Length..]
: bodyId;

if (!Guid.TryParse(guidText, out _))
{
throw new ArgumentException("The body id must be a GUID, optionally prefixed with 'failedimport-'.", nameof(bodyId));
}

return Path.Combine(StoragePath, $"{bodyId}.body");
}

static void TryDelete(string filePath)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,23 +17,24 @@ public Task RecordFailedProcessingAttempt(MessageContext context,
List<FailedMessage.FailureGroup> groups,
CancellationToken cancellationToken = default)
{
var uniqueMessageId = context.Headers.UniqueId();
var uniqueMessageIdString = context.Headers.UniqueId();
var uniqueMessageId = Guid.TryParse(uniqueMessageIdString, out var parsed) ? parsed : DeterministicGuid.MakeId(uniqueMessageIdString);
var contentType = context.Headers.GetValueOrDefault(Headers.ContentType, "text/plain");
var bodySize = context.Body.Length;
var (bodyText, storeExternally) = MessageBodyClassifier.Classify(context.Headers, context.Body, settings.BodyStorage.MaxBodySizeToStore);

if (storeExternally)
{
parentUnitOfWork.RecordBodyWrite(
storagePersistence.WriteBody(uniqueMessageId, context.Body, contentType, cancellationToken));
storagePersistence.WriteBody(uniqueMessageId.ToString(), context.Body, contentType, cancellationToken));
}

var sendingEndpoint = GetMetadata<EndpointDetails>(processingAttempt, "SendingEndpoint");
var receivingEndpoint = GetMetadata<EndpointDetails>(processingAttempt, "ReceivingEndpoint");

parentUnitOfWork.Record(new RecordedFailedProcessingAttempt
{
UniqueMessageId = Guid.Parse(uniqueMessageId),
UniqueMessageId = uniqueMessageId,
AttemptedAt = processingAttempt.AttemptedAt,
TimeOfFailure = processingAttempt.FailureDetails.TimeOfFailure,
Groups = groups,
Expand Down
Loading
Loading