feat(auditlog): NotifyDeliver rows carry the originating ExecutionId
This commit is contained in:
@@ -27,6 +27,15 @@ public class Notification
|
||||
public string SourceSiteId { get; set; }
|
||||
public string? SourceInstanceId { get; set; }
|
||||
public string? SourceScript { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The originating script execution's <c>ExecutionId</c> (Audit Log #23). Carried from
|
||||
/// the site on the <see cref="Commons.Messages.Notification.NotificationSubmit"/> so the
|
||||
/// central dispatcher can stamp the same id onto its <c>NotifyDeliver</c> audit rows,
|
||||
/// correlating them with the site-emitted <c>NotifySend</c> row. Null for notifications
|
||||
/// submitted before the column existed, or raised outside a script-execution context.
|
||||
/// </summary>
|
||||
public Guid? OriginExecutionId { get; set; }
|
||||
public DateTimeOffset SiteEnqueuedAt { get; set; }
|
||||
|
||||
/// <summary>Central ingest time.</summary>
|
||||
|
||||
@@ -4,6 +4,13 @@ namespace ScadaLink.Commons.Messages.Notification;
|
||||
/// Site -> Central: submit a notification for central delivery.
|
||||
/// Fire-and-forget with ack; the site retries until a <see cref="NotificationSubmitAck"/> is received.
|
||||
/// </summary>
|
||||
/// <param name="OriginExecutionId">
|
||||
/// The originating script execution's <c>ExecutionId</c> (Audit Log #23). Stamped at
|
||||
/// <c>Notify.Send</c> time and carried, inside the serialized payload, through the site
|
||||
/// store-and-forward buffer so the central dispatcher can echo it onto the
|
||||
/// <c>NotifyDeliver</c> audit rows. Additive trailing member — null for messages built
|
||||
/// before the field existed, or for notifications raised outside a script execution.
|
||||
/// </param>
|
||||
public record NotificationSubmit(
|
||||
string NotificationId,
|
||||
string ListName,
|
||||
@@ -12,7 +19,8 @@ public record NotificationSubmit(
|
||||
string SourceSiteId,
|
||||
string? SourceInstanceId,
|
||||
string? SourceScript,
|
||||
DateTimeOffset SiteEnqueuedAt);
|
||||
DateTimeOffset SiteEnqueuedAt,
|
||||
Guid? OriginExecutionId = null);
|
||||
|
||||
/// <summary>
|
||||
/// Central -> Site: ack sent after the notification row is persisted.
|
||||
|
||||
@@ -47,6 +47,10 @@ public class NotificationOutboxConfiguration : IEntityTypeConfiguration<Notifica
|
||||
|
||||
builder.Property(n => n.SourceScript).HasMaxLength(200);
|
||||
|
||||
// OriginExecutionId (Audit Log #23): nullable uniqueidentifier carried from the
|
||||
// site so the dispatcher can echo it onto NotifyDeliver audit rows. No index —
|
||||
// it is never a query predicate on this table, only copied onto audit events.
|
||||
|
||||
builder.HasIndex(n => new { n.Status, n.NextAttemptAt });
|
||||
|
||||
builder.HasIndex(n => new { n.SourceSiteId, n.CreatedAt });
|
||||
|
||||
1629
src/ScadaLink.ConfigurationDatabase/Migrations/20260521193048_AddNotificationOriginExecutionId.Designer.cs
generated
Normal file
1629
src/ScadaLink.ConfigurationDatabase/Migrations/20260521193048_AddNotificationOriginExecutionId.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,41 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace ScadaLink.ConfigurationDatabase.Migrations
|
||||
{
|
||||
/// <summary>
|
||||
/// Adds the <c>OriginExecutionId</c> correlation column to the central
|
||||
/// <c>Notifications</c> table (#21). It carries the originating script execution's
|
||||
/// <c>ExecutionId</c> from the site so the dispatcher can echo it onto the
|
||||
/// <c>NotifyDeliver</c> audit rows (#23), linking them to the site's <c>NotifySend</c>
|
||||
/// row for the same run.
|
||||
///
|
||||
/// The change is purely additive: <c>OriginExecutionId uniqueidentifier NULL</c> is
|
||||
/// added with no default, so the operation is a metadata-only <c>ALTER TABLE … ADD</c>.
|
||||
/// Unlike <c>AuditLog</c>, the <c>Notifications</c> table is NOT partitioned, so a
|
||||
/// plain <c>ADD</c> is fine. No index is created — the column is never a query
|
||||
/// predicate, only copied onto audit events. Historical rows stay <c>NULL</c>.
|
||||
/// </summary>
|
||||
public partial class AddNotificationOriginExecutionId : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<Guid>(
|
||||
name: "OriginExecutionId",
|
||||
table: "Notifications",
|
||||
type: "uniqueidentifier",
|
||||
nullable: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "OriginExecutionId",
|
||||
table: "Notifications");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -787,6 +787,9 @@ namespace ScadaLink.ConfigurationDatabase.Migrations
|
||||
b.Property<DateTimeOffset?>("NextAttemptAt")
|
||||
.HasColumnType("datetimeoffset");
|
||||
|
||||
b.Property<Guid?>("OriginExecutionId")
|
||||
.HasColumnType("uniqueidentifier");
|
||||
|
||||
b.Property<string>("ResolvedTargets")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
|
||||
@@ -489,6 +489,10 @@ public class NotificationOutboxActor : ReceiveActor, IWithTimers
|
||||
/// parses the notification's id as a Guid; sites generate the id with
|
||||
/// <c>Guid.NewGuid().ToString("N")</c> so the parse always succeeds, but
|
||||
/// a non-Guid id is recorded as null rather than crashing the dispatcher.
|
||||
/// <see cref="AuditEvent.ExecutionId"/> is copied straight from
|
||||
/// <see cref="Notification.OriginExecutionId"/> so the dispatcher's
|
||||
/// <c>NotifyDeliver</c> rows carry the same per-run id as the site's
|
||||
/// <c>NotifySend</c> row (Audit Log #23).
|
||||
/// </summary>
|
||||
private static AuditEvent BuildNotifyDeliverEvent(
|
||||
Notification notification,
|
||||
@@ -515,6 +519,12 @@ public class NotificationOutboxActor : ReceiveActor, IWithTimers
|
||||
SourceSiteId = notification.SourceSiteId,
|
||||
SourceInstanceId = notification.SourceInstanceId,
|
||||
SourceScript = notification.SourceScript,
|
||||
// ExecutionId (Audit Log #23): the originating script execution's id,
|
||||
// carried from the site on NotificationSubmit and persisted on the
|
||||
// Notification row. Echoing it here links the central NotifyDeliver
|
||||
// rows to the site-emitted NotifySend row for the same run. Null when
|
||||
// the notification was raised outside a script execution.
|
||||
ExecutionId = notification.OriginExecutionId,
|
||||
Target = notification.ListName,
|
||||
Status = status,
|
||||
ErrorMessage = errorMessage,
|
||||
@@ -941,6 +951,9 @@ public class NotificationOutboxActor : ReceiveActor, IWithTimers
|
||||
{
|
||||
SourceInstanceId = msg.SourceInstanceId,
|
||||
SourceScript = msg.SourceScript,
|
||||
// OriginExecutionId (Audit Log #23): the originating script execution's id,
|
||||
// carried from the site so the dispatcher can echo it onto NotifyDeliver rows.
|
||||
OriginExecutionId = msg.OriginExecutionId,
|
||||
SiteEnqueuedAt = msg.SiteEnqueuedAt,
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
// Status stays at its Pending default for the dispatch sweep to claim.
|
||||
|
||||
@@ -1407,7 +1407,12 @@ public class ScriptRuntimeContext
|
||||
// notification, threaded down from the script-execution context for the
|
||||
// central audit trail. Null when no single script owns the context.
|
||||
SourceScript: _sourceScript,
|
||||
SiteEnqueuedAt: DateTimeOffset.UtcNow);
|
||||
SiteEnqueuedAt: DateTimeOffset.UtcNow,
|
||||
// OriginExecutionId (Audit Log #23): the SAME per-execution id stamped
|
||||
// onto this run's NotifySend audit row. It rides inside the serialized
|
||||
// payload through the S&F buffer to central, where the dispatcher echoes
|
||||
// it onto the NotifyDeliver rows so all rows for one run share an id.
|
||||
OriginExecutionId: _executionId);
|
||||
|
||||
var payloadJson = JsonSerializer.Serialize(payload);
|
||||
|
||||
|
||||
@@ -21,6 +21,21 @@ public class NotificationEntityTests
|
||||
Assert.Equal("SiteA", n.SourceSiteId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OriginExecutionId_DefaultsToNull_AndIsSettable()
|
||||
{
|
||||
// Audit Log #23: OriginExecutionId carries the originating script
|
||||
// execution's id from the site so the dispatcher can echo it onto
|
||||
// NotifyDeliver rows. Null for notifications submitted before the
|
||||
// column existed; settable from the NotificationSubmit message.
|
||||
var n = new Notification("id-1", NotificationType.Email, "ops-team", "subj", "body", "SiteA");
|
||||
Assert.Null(n.OriginExecutionId);
|
||||
|
||||
var executionId = Guid.NewGuid();
|
||||
n.OriginExecutionId = executionId;
|
||||
Assert.Equal(executionId, n.OriginExecutionId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_NullArguments_Throw()
|
||||
{
|
||||
|
||||
@@ -40,6 +40,47 @@ public class NotificationMessagesTests
|
||||
Assert.Null(msg.SourceScript);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NotificationSubmit_OriginExecutionId_DefaultsToNull()
|
||||
{
|
||||
// Audit Log #23: OriginExecutionId is an additive trailing member — a
|
||||
// submit built without it (old call sites / old serialized payloads)
|
||||
// leaves the id null.
|
||||
var msg = new NotificationSubmit(
|
||||
"notif-3", "Operators", "Subject", "Body",
|
||||
"site-01", "inst-1", "OnAlarm", DateTimeOffset.UtcNow);
|
||||
|
||||
Assert.Null(msg.OriginExecutionId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NotificationSubmit_OriginExecutionId_RoundTripsWhenSupplied()
|
||||
{
|
||||
var executionId = Guid.NewGuid();
|
||||
var msg = new NotificationSubmit(
|
||||
"notif-4", "Operators", "Subject", "Body",
|
||||
"site-01", "inst-1", "OnAlarm", DateTimeOffset.UtcNow, executionId);
|
||||
|
||||
Assert.Equal(executionId, msg.OriginExecutionId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NotificationSubmit_OriginExecutionId_SurvivesJsonRoundTrip()
|
||||
{
|
||||
// The buffered S&F payload IS a serialized NotificationSubmit; the
|
||||
// forwarder deserializes it, so OriginExecutionId must survive JSON.
|
||||
var executionId = Guid.NewGuid();
|
||||
var msg = new NotificationSubmit(
|
||||
"notif-5", "Operators", "Subject", "Body",
|
||||
"site-01", "inst-1", "OnAlarm", DateTimeOffset.UtcNow, executionId);
|
||||
|
||||
var json = System.Text.Json.JsonSerializer.Serialize(msg);
|
||||
var roundTripped = System.Text.Json.JsonSerializer.Deserialize<NotificationSubmit>(json);
|
||||
|
||||
Assert.NotNull(roundTripped);
|
||||
Assert.Equal(executionId, roundTripped!.OriginExecutionId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NotificationSubmit_ValueEquality_EqualWhenAllFieldsMatch()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
using Xunit;
|
||||
|
||||
namespace ScadaLink.ConfigurationDatabase.Tests.Migrations;
|
||||
|
||||
/// <summary>
|
||||
/// Audit Log #23 (ExecutionId Task 5) integration test for the
|
||||
/// <c>AddNotificationOriginExecutionId</c> migration: applies the EF migrations
|
||||
/// to a freshly-created MSSQL test database on the running infra/mssql container
|
||||
/// and asserts that the <c>Notifications</c> table carries the new
|
||||
/// <c>OriginExecutionId</c> column as a nullable <c>uniqueidentifier</c>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Unlike <c>AuditLog</c>, the <c>Notifications</c> table is not partitioned, so
|
||||
/// the column is a plain metadata-only <c>ALTER TABLE … ADD</c> with no index.
|
||||
/// Tests pair <see cref="SkippableFactAttribute"/> with <c>Skip.IfNot(...)</c> so
|
||||
/// the runner reports them as Skipped (not Passed) when MSSQL is unreachable. The
|
||||
/// fixture applies the migrations once at construction time.
|
||||
/// </remarks>
|
||||
public class AddNotificationOriginExecutionIdMigrationTests : IClassFixture<MsSqlMigrationFixture>
|
||||
{
|
||||
private readonly MsSqlMigrationFixture _fixture;
|
||||
|
||||
public AddNotificationOriginExecutionIdMigrationTests(MsSqlMigrationFixture fixture)
|
||||
{
|
||||
_fixture = fixture;
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task AppliesMigration_AddsOriginExecutionIdColumn_ToNotifications()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
|
||||
var present = await ScalarAsync<int>(
|
||||
"SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS " +
|
||||
"WHERE TABLE_NAME = 'Notifications' AND COLUMN_NAME = 'OriginExecutionId' " +
|
||||
"AND TABLE_SCHEMA = 'dbo';");
|
||||
Assert.Equal(1, present);
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task OriginExecutionIdColumn_IsNullableUniqueIdentifier()
|
||||
{
|
||||
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
|
||||
|
||||
var dataType = await ScalarAsync<string?>(
|
||||
"SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS " +
|
||||
"WHERE TABLE_NAME = 'Notifications' AND COLUMN_NAME = 'OriginExecutionId';");
|
||||
Assert.Equal("uniqueidentifier", dataType);
|
||||
|
||||
var isNullable = await ScalarAsync<string?>(
|
||||
"SELECT IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS " +
|
||||
"WHERE TABLE_NAME = 'Notifications' AND COLUMN_NAME = 'OriginExecutionId';");
|
||||
Assert.Equal("YES", isNullable);
|
||||
}
|
||||
|
||||
// --- helpers ------------------------------------------------------------
|
||||
|
||||
private async Task<T> ScalarAsync<T>(string sql)
|
||||
{
|
||||
await using var conn = _fixture.OpenConnection();
|
||||
await using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = sql;
|
||||
var result = await cmd.ExecuteScalarAsync();
|
||||
if (result is null || result is DBNull)
|
||||
{
|
||||
return default!;
|
||||
}
|
||||
return (T)Convert.ChangeType(result, typeof(T) == typeof(string) ? typeof(string) : Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T))!;
|
||||
}
|
||||
}
|
||||
@@ -268,6 +268,7 @@ public class NotificationOutboxConfigurationTests : IDisposable
|
||||
var lastAttemptAt = new DateTimeOffset(2026, 5, 19, 8, 1, 0, TimeSpan.Zero);
|
||||
var nextAttemptAt = new DateTimeOffset(2026, 5, 19, 8, 2, 0, TimeSpan.Zero);
|
||||
var deliveredAt = new DateTimeOffset(2026, 5, 19, 8, 3, 0, TimeSpan.Zero);
|
||||
var originExecutionId = Guid.NewGuid();
|
||||
|
||||
var notification = new Notification(id, NotificationType.Email, "Ops List",
|
||||
"High Tank Level", "Tank 4 exceeded the high level threshold.", "site-north")
|
||||
@@ -279,6 +280,7 @@ public class NotificationOutboxConfigurationTests : IDisposable
|
||||
ResolvedTargets = "ops@example.test;duty@example.test",
|
||||
SourceInstanceId = "instance-42",
|
||||
SourceScript = "TankLevelAlarm",
|
||||
OriginExecutionId = originExecutionId,
|
||||
SiteEnqueuedAt = siteEnqueuedAt,
|
||||
CreatedAt = createdAt,
|
||||
LastAttemptAt = lastAttemptAt,
|
||||
@@ -311,6 +313,27 @@ public class NotificationOutboxConfigurationTests : IDisposable
|
||||
Assert.Equal(lastAttemptAt, loaded.LastAttemptAt);
|
||||
Assert.Equal(nextAttemptAt, loaded.NextAttemptAt);
|
||||
Assert.Equal(deliveredAt, loaded.DeliveredAt);
|
||||
Assert.Equal(originExecutionId, loaded.OriginExecutionId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Notification_NullOriginExecutionId_RoundTripsAsNull()
|
||||
{
|
||||
// Audit Log #23: OriginExecutionId is an additive nullable column —
|
||||
// notifications raised outside a script execution (or submitted before
|
||||
// the column existed) persist and reload it as null.
|
||||
var id = Guid.NewGuid().ToString();
|
||||
var notification = new Notification(id, NotificationType.Email, "Ops List",
|
||||
"Subject", "Body", "site-north");
|
||||
|
||||
_context.Notifications.Add(notification);
|
||||
await _context.SaveChangesAsync();
|
||||
_context.ChangeTracker.Clear();
|
||||
|
||||
var loaded = await _context.Notifications.FindAsync(id);
|
||||
|
||||
Assert.NotNull(loaded);
|
||||
Assert.Null(loaded!.OriginExecutionId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -94,7 +94,8 @@ public class NotificationOutboxActorAttemptEmissionTests : TestKit
|
||||
private static Notification MakeNotification(
|
||||
Guid? notificationId = null,
|
||||
string sourceSite = "site-1",
|
||||
int retryCount = 0)
|
||||
int retryCount = 0,
|
||||
Guid? originExecutionId = null)
|
||||
{
|
||||
return new Notification(
|
||||
(notificationId ?? Guid.NewGuid()).ToString("D"),
|
||||
@@ -108,6 +109,7 @@ public class NotificationOutboxActorAttemptEmissionTests : TestKit
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
SourceInstanceId = "instance-42",
|
||||
SourceScript = "AlarmScript",
|
||||
OriginExecutionId = originExecutionId,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -162,6 +164,49 @@ public class NotificationOutboxActorAttemptEmissionTests : TestKit
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Attempt_CarriesOriginExecutionId_AsExecutionId()
|
||||
{
|
||||
// Audit Log #23: the Attempted NotifyDeliver row must echo the
|
||||
// notification's OriginExecutionId so all rows for one run share an id.
|
||||
SetupSmtpRetryPolicy(maxRetries: 5, retryDelay: TimeSpan.FromMinutes(1));
|
||||
var executionId = Guid.NewGuid();
|
||||
var notification = MakeNotification(originExecutionId: executionId);
|
||||
_outboxRepository.GetDueAsync(Arg.Any<DateTimeOffset>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new[] { notification });
|
||||
var adapter = new StubAdapter(() => DeliveryOutcome.Success("ops@example.com"));
|
||||
var actor = CreateActor([adapter]);
|
||||
|
||||
actor.Tell(InternalMessages.DispatchTick.Instance);
|
||||
|
||||
AwaitAssert(() =>
|
||||
{
|
||||
var attempted = EventsByStatus(AuditStatus.Attempted);
|
||||
Assert.Single(attempted);
|
||||
Assert.Equal(executionId, attempted[0].ExecutionId);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Attempt_NullOriginExecutionId_HasNullExecutionId()
|
||||
{
|
||||
SetupSmtpRetryPolicy(maxRetries: 5, retryDelay: TimeSpan.FromMinutes(1));
|
||||
var notification = MakeNotification(originExecutionId: null);
|
||||
_outboxRepository.GetDueAsync(Arg.Any<DateTimeOffset>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new[] { notification });
|
||||
var adapter = new StubAdapter(() => DeliveryOutcome.Success("ops@example.com"));
|
||||
var actor = CreateActor([adapter]);
|
||||
|
||||
actor.Tell(InternalMessages.DispatchTick.Instance);
|
||||
|
||||
AwaitAssert(() =>
|
||||
{
|
||||
var attempted = EventsByStatus(AuditStatus.Attempted);
|
||||
Assert.Single(attempted);
|
||||
Assert.Null(attempted[0].ExecutionId);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Attempt_TransientFailure_EmitsEvent_StatusAttempted_ErrorMessageSet()
|
||||
{
|
||||
|
||||
@@ -39,7 +39,8 @@ public class NotificationOutboxActorIngestTests : TestKit
|
||||
NullLogger<NotificationOutboxActor>.Instance)));
|
||||
}
|
||||
|
||||
private static NotificationSubmit MakeSubmit(string? notificationId = null)
|
||||
private static NotificationSubmit MakeSubmit(
|
||||
string? notificationId = null, Guid? originExecutionId = null)
|
||||
{
|
||||
return new NotificationSubmit(
|
||||
NotificationId: notificationId ?? Guid.NewGuid().ToString(),
|
||||
@@ -49,7 +50,8 @@ public class NotificationOutboxActorIngestTests : TestKit
|
||||
SourceSiteId: "site-1",
|
||||
SourceInstanceId: "instance-42",
|
||||
SourceScript: "AlarmScript",
|
||||
SiteEnqueuedAt: new DateTimeOffset(2026, 5, 19, 8, 30, 0, TimeSpan.Zero));
|
||||
SiteEnqueuedAt: new DateTimeOffset(2026, 5, 19, 8, 30, 0, TimeSpan.Zero),
|
||||
OriginExecutionId: originExecutionId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -83,6 +85,42 @@ public class NotificationOutboxActorIngestTests : TestKit
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NotificationSubmit_CopiesOriginExecutionId_OntoPersistedNotification()
|
||||
{
|
||||
// Audit Log #23: the originating script execution's id rides on the
|
||||
// NotificationSubmit and must be persisted on the Notification row so
|
||||
// the dispatcher can later echo it onto NotifyDeliver audit rows.
|
||||
_repository.InsertIfNotExistsAsync(Arg.Any<Notification>(), Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
var executionId = Guid.NewGuid();
|
||||
var submit = MakeSubmit(originExecutionId: executionId);
|
||||
var actor = CreateActor();
|
||||
|
||||
actor.Tell(submit, TestActor);
|
||||
|
||||
ExpectMsg<NotificationSubmitAck>();
|
||||
_repository.Received(1).InsertIfNotExistsAsync(
|
||||
Arg.Is<Notification>(n => n.OriginExecutionId == executionId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NotificationSubmit_NullOriginExecutionId_PersistsNull()
|
||||
{
|
||||
_repository.InsertIfNotExistsAsync(Arg.Any<Notification>(), Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
var submit = MakeSubmit(originExecutionId: null);
|
||||
var actor = CreateActor();
|
||||
|
||||
actor.Tell(submit, TestActor);
|
||||
|
||||
ExpectMsg<NotificationSubmitAck>();
|
||||
_repository.Received(1).InsertIfNotExistsAsync(
|
||||
Arg.Is<Notification>(n => n.OriginExecutionId == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DuplicateSubmit_RepositoryReturnsFalse_StillAcksAccepted()
|
||||
{
|
||||
|
||||
@@ -87,7 +87,8 @@ public class NotificationOutboxActorTerminalEmissionTests : TestKit
|
||||
private static Notification MakeNotification(
|
||||
NotificationStatus status = NotificationStatus.Pending,
|
||||
int retryCount = 0,
|
||||
Guid? notificationId = null)
|
||||
Guid? notificationId = null,
|
||||
Guid? originExecutionId = null)
|
||||
{
|
||||
return new Notification(
|
||||
(notificationId ?? Guid.NewGuid()).ToString("D"),
|
||||
@@ -100,6 +101,7 @@ public class NotificationOutboxActorTerminalEmissionTests : TestKit
|
||||
Status = status,
|
||||
RetryCount = retryCount,
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
OriginExecutionId = originExecutionId,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -145,6 +147,50 @@ public class NotificationOutboxActorTerminalEmissionTests : TestKit
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Terminal_Delivered_CarriesOriginExecutionId_AsExecutionId()
|
||||
{
|
||||
// Audit Log #23: the terminal NotifyDeliver row must echo the
|
||||
// notification's OriginExecutionId so it shares the per-run id with
|
||||
// the site-emitted NotifySend row.
|
||||
SetupSmtpRetryPolicy(maxRetries: 5, retryDelay: TimeSpan.FromMinutes(1));
|
||||
var executionId = Guid.NewGuid();
|
||||
var notification = MakeNotification(originExecutionId: executionId);
|
||||
_outboxRepository.GetDueAsync(Arg.Any<DateTimeOffset>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new[] { notification });
|
||||
var adapter = new StubAdapter(() => DeliveryOutcome.Success("ops@example.com"));
|
||||
var actor = CreateActor([adapter]);
|
||||
|
||||
actor.Tell(InternalMessages.DispatchTick.Instance);
|
||||
|
||||
AwaitAssert(() =>
|
||||
{
|
||||
var delivered = EventsByStatus(AuditStatus.Delivered);
|
||||
Assert.Single(delivered);
|
||||
Assert.Equal(executionId, delivered[0].ExecutionId);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Terminal_Delivered_NullOriginExecutionId_HasNullExecutionId()
|
||||
{
|
||||
SetupSmtpRetryPolicy(maxRetries: 5, retryDelay: TimeSpan.FromMinutes(1));
|
||||
var notification = MakeNotification(originExecutionId: null);
|
||||
_outboxRepository.GetDueAsync(Arg.Any<DateTimeOffset>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new[] { notification });
|
||||
var adapter = new StubAdapter(() => DeliveryOutcome.Success("ops@example.com"));
|
||||
var actor = CreateActor([adapter]);
|
||||
|
||||
actor.Tell(InternalMessages.DispatchTick.Instance);
|
||||
|
||||
AwaitAssert(() =>
|
||||
{
|
||||
var delivered = EventsByStatus(AuditStatus.Delivered);
|
||||
Assert.Single(delivered);
|
||||
Assert.Null(delivered[0].ExecutionId);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Terminal_Parked_OnPermanentFailure_EmitsEvent_StatusParked()
|
||||
{
|
||||
|
||||
@@ -60,7 +60,8 @@ public class NotifyHelperTests : TestKit, IAsyncLifetime, IDisposable
|
||||
|
||||
private ScriptRuntimeContext.NotifyHelper CreateHelper(
|
||||
IActorRef siteCommunicationActor,
|
||||
string? sourceScript = null)
|
||||
string? sourceScript = null,
|
||||
Guid? executionId = null)
|
||||
{
|
||||
return new ScriptRuntimeContext.NotifyHelper(
|
||||
_saf,
|
||||
@@ -70,7 +71,7 @@ public class NotifyHelperTests : TestKit, IAsyncLifetime, IDisposable
|
||||
sourceScript,
|
||||
TimeSpan.FromSeconds(3),
|
||||
NullLogger.Instance,
|
||||
Guid.NewGuid());
|
||||
executionId ?? Guid.NewGuid());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -134,6 +135,27 @@ public class NotifyHelperTests : TestKit, IAsyncLifetime, IDisposable
|
||||
Assert.Equal("ScriptActor:MonitorSpeed", payload!.SourceScript);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Send_StampsExecutionId_OnTheNotificationSubmitPayload()
|
||||
{
|
||||
// Audit Log #23 (ExecutionId Task 5): Notify.Send must stamp the
|
||||
// script run's ExecutionId onto the NotificationSubmit so it rides
|
||||
// inside the serialized S&F payload to central, where the dispatcher
|
||||
// echoes it onto the NotifyDeliver rows. This is the SAME id stamped
|
||||
// onto the site-emitted NotifySend audit row.
|
||||
var executionId = Guid.NewGuid();
|
||||
var commProbe = CreateTestProbe();
|
||||
var notify = CreateHelper(commProbe.Ref, executionId: executionId);
|
||||
|
||||
var notificationId = await notify.To("Operators").Send("Pump alarm", "Pump 3 tripped");
|
||||
|
||||
var buffered = await _saf.GetMessageByIdAsync(notificationId);
|
||||
Assert.NotNull(buffered);
|
||||
var payload = JsonSerializer.Deserialize<NotificationSubmit>(buffered!.PayloadJson);
|
||||
Assert.NotNull(payload);
|
||||
Assert.Equal(executionId, payload!.OriginExecutionId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Send_WhenHelperHasNoSourceScript_LeavesSourceScriptNull()
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user