Repository navigation
Expand file tree
/
Copy pathTemplateEmailNotifier.cs
More file actions
202 lines (179 loc) · 7.79 KB
/
Copy pathTemplateEmailNotifier.cs
File metadata and controls
202 lines (179 loc) · 7.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
using BlazorWebForms.Core.Abstractions;
using BlazorWebForms.Core.Models;
using Microsoft.Extensions.Logging;
namespace BlazorWebForms.Infrastructure.SqlServer;
internal sealed class TemplateEmailNotifier(
BlazorWebFormsSqlServerOptions options,
IEmailIntegration emailIntegration,
IGraphIntegration graphIntegration,
IAntiAbuseGuard antiAbuseGuard,
IOperationalTelemetry telemetry,
ILogger<TemplateEmailNotifier> logger) : IEmailNotifier
{
private readonly HashSet<string> sentKeys = new(StringComparer.Ordinal);
public Task NotifyManagersAsync(FormAggregate form, EntryRecord entry, CancellationToken cancellationToken = default)
{
if (!options.EnableOutboundEmail)
{
return Task.CompletedTask;
}
return SendWithRetryAsync($"submit:{entry.Id}",
$"New submission: {form.Name}",
$"A new entry was submitted to '{form.Name}'.", cancellationToken);
}
public Task<string?> NotifyApproverAssignedAsync(FormAggregate form, EntryRecord entry, ApprovalStepRecord step, string idempotencyKey, CancellationToken cancellationToken = default)
{
if (!options.EnableOutboundEmail)
{
return Task.FromResult<string?>(null);
}
return SendWithRetryAsync($"assigned:{idempotencyKey}",
$"Approval requested: {form.Name}",
$"You are assigned to approve an entry for form '{form.Name}'.",
async ct =>
{
if (!options.EnableGraphIntegration)
{
return null;
}
var result = await graphIntegration.SendApprovalReminderAsync(form, entry, step, ct);
result.Data.TryGetValue("correlationId", out var correlationId);
return correlationId;
},
cancellationToken);
}
public Task<string?> NotifyApproverReminderAsync(FormAggregate form, EntryRecord entry, ApprovalStepRecord step, string idempotencyKey, CancellationToken cancellationToken = default)
{
if (!options.EnableOutboundEmail)
{
return Task.FromResult<string?>(null);
}
return SendWithRetryAsync($"reminder:{idempotencyKey}",
$"Approval reminder: {form.Name}",
$"Reminder: an entry is waiting for your approval.",
async ct =>
{
if (options.EnableGraphIntegration)
{
var result = await graphIntegration.SendApprovalReminderAsync(form, entry, step, ct);
result.Data.TryGetValue("correlationId", out var correlationId);
return correlationId;
}
return null;
},
cancellationToken);
}
public Task NotifyEntryApprovedAsync(FormAggregate form, EntryRecord entry, CancellationToken cancellationToken = default)
{
if (!options.EnableOutboundEmail)
{
return Task.CompletedTask;
}
return SendWithRetryAsync($"approved:{entry.Id}",
$"Entry approved: {form.Name}",
$"Your submission has been approved.", cancellationToken);
}
public Task NotifyEntryRejectedAsync(FormAggregate form, EntryRecord entry, ApprovalStepRecord step, CancellationToken cancellationToken = default)
{
if (!options.EnableOutboundEmail)
{
return Task.CompletedTask;
}
return SendWithRetryAsync($"rejected:{entry.Id}:{step.Id}",
$"Entry rejected: {form.Name}",
$"Your submission was rejected. Reason: {step.RejectionReason}", cancellationToken);
}
public Task NotifyInvitationCreatedAsync(FormAggregate form, FormInvitation invitation, CancellationToken cancellationToken = default)
{
if (!options.EnableOutboundEmail)
{
return Task.CompletedTask;
}
return SendWithRetryAsync($"invite-created:{invitation.Id}",
$"Invitation to {form.Name}",
$"You have been invited as {invitation.Role}.",
async ct =>
{
if (options.EnableGraphIntegration)
{
var result = await graphIntegration.SendInvitationAsync(form, invitation, ct);
result.Data.TryGetValue("correlationId", out var correlationId);
return correlationId;
}
return null;
},
cancellationToken);
}
public Task NotifyInvitationAcceptedAsync(FormAggregate form, FormInvitation invitation, CancellationToken cancellationToken = default)
{
if (!options.EnableOutboundEmail)
{
return Task.CompletedTask;
}
return SendWithRetryAsync($"invite-accepted:{invitation.Id}",
$"Invitation accepted: {form.Name}",
$"Invitation for {invitation.Email} was accepted.", cancellationToken);
}
public Task NotifyInvitationRevokedAsync(FormAggregate form, FormInvitation invitation, CancellationToken cancellationToken = default)
{
if (!options.EnableOutboundEmail)
{
return Task.CompletedTask;
}
return SendWithRetryAsync($"invite-revoked:{invitation.Id}",
$"Invitation revoked: {form.Name}",
$"Invitation for {invitation.Email} was revoked.", cancellationToken);
}
private async Task<string?> SendWithRetryAsync(string key, string subject, string body, CancellationToken cancellationToken)
{
return await SendWithRetryAsync(key, subject, body, null, cancellationToken);
}
private async Task<string?> SendWithRetryAsync(
string key,
string subject,
string body,
Func<CancellationToken, Task<string?>>? afterSend,
CancellationToken cancellationToken)
{
if (!sentKeys.Add(key))
{
logger.LogDebug("Skipping duplicate email notification for key {NotificationKey}.", key);
return null;
}
Exception? last = null;
for (var attempt = 1; attempt <= options.EmailRetryCount; attempt++)
{
try
{
await antiAbuseGuard.CheckOutboundNotificationAllowedAsync("email", "integration@example.com", cancellationToken);
await emailIntegration.SendAsync("integration@example.com", subject, body, cancellationToken);
telemetry.TrackEmailDelivery("email", success: true);
if (afterSend is not null)
{
return await afterSend(cancellationToken);
}
return null;
}
catch (Exception ex) when (attempt < options.EmailRetryCount)
{
last = ex;
telemetry.TrackEmailDelivery("email", success: false);
telemetry.TrackFailure("email", "send", ex.GetType().Name);
logger.LogWarning(ex, "Email delivery attempt {Attempt} failed for key {NotificationKey}. Retrying.", attempt, key);
await Task.Delay(TimeSpan.FromMilliseconds(options.EmailRetryDelayMs), cancellationToken);
}
catch (Exception ex)
{
last = ex;
telemetry.TrackEmailDelivery("email", success: false);
telemetry.TrackFailure("email", "send", ex.GetType().Name);
logger.LogError(ex, "Email delivery failed on final attempt {Attempt} for key {NotificationKey}.", attempt, key);
break;
}
}
logger.LogError(last, "Email delivery failed after {RetryCount} attempts for key {NotificationKey}.", options.EmailRetryCount, key);
throw new InvalidOperationException(
$"Email delivery failed after {options.EmailRetryCount} attempt(s) for key '{key}'.",
last);
}
}