-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathRavenRecoverabilityIngestionUnitOfWork.cs
More file actions
179 lines (148 loc) · 8.31 KB
/
RavenRecoverabilityIngestionUnitOfWork.cs
File metadata and controls
179 lines (148 loc) · 8.31 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
namespace ServiceControl.Persistence.RavenDB
{
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using NServiceBus;
using NServiceBus.Transport;
using Raven.Client.Documents.Commands.Batches;
using Raven.Client.Documents.Operations;
using ServiceControl.Infrastructure;
using ServiceControl.MessageFailures;
using ServiceControl.Persistence.Infrastructure;
using ServiceControl.Persistence.UnitOfWork;
using ServiceControl.Recoverability;
class RavenRecoverabilityIngestionUnitOfWork : IRecoverabilityIngestionUnitOfWork
{
readonly RavenIngestionUnitOfWork parentUnitOfWork;
readonly ExpirationManager expirationManager;
readonly bool doFullTextIndexing;
public RavenRecoverabilityIngestionUnitOfWork(RavenIngestionUnitOfWork parentUnitOfWork, ExpirationManager expirationManager, RavenPersisterSettings settings)
{
this.parentUnitOfWork = parentUnitOfWork;
this.expirationManager = expirationManager;
doFullTextIndexing = settings.EnableFullTextSearchOnBodies;
}
public Task RecordFailedProcessingAttempt(
MessageContext context,
FailedMessage.ProcessingAttempt processingAttempt,
List<FailedMessage.FailureGroup> groups)
{
var uniqueMessageId = GetUniqueMessageId(context);
var contentType = GetContentType(context.Headers, "text/xml");
var bodySize = context.Body.Length;
processingAttempt.MessageMetadata.Add("ContentType", contentType);
processingAttempt.MessageMetadata.Add("ContentLength", bodySize);
processingAttempt.MessageMetadata.Add("BodyUrl", $"/messages/{uniqueMessageId}/body");
if (doFullTextIndexing)
{
var avoidsLargeObjectHeap = bodySize < LargeObjectHeapThreshold;
var isBinary = processingAttempt.Headers.IsBinary();
if (avoidsLargeObjectHeap && !isBinary)
{
try
{
var bodyString = utf8.GetString(context.Body.Span);
processingAttempt.MessageMetadata.Add("MsgFullText", bodyString);
}
catch (ArgumentException)
{
// If it won't decode to text, don't index it
}
}
}
var storeMessageCmd = CreateFailedMessagesPatchCommand(uniqueMessageId, processingAttempt, groups);
parentUnitOfWork.AddCommand(storeMessageCmd);
AddStoreBodyCommands(uniqueMessageId, context, contentType);
return Task.CompletedTask;
}
public Task RecordSuccessfulRetry(string retriedMessageUniqueId)
{
var failedMessageDocumentId = FailedMessageIdGenerator.MakeDocumentId(retriedMessageUniqueId);
var failedMessageRetryDocumentId = FailedMessageRetry.MakeDocumentId(retriedMessageUniqueId);
var patchRequest = new PatchRequest { Script = $@"this.{nameof(FailedMessage.Status)} = {(int)FailedMessageStatus.Resolved};" };
expirationManager.EnableExpiration(patchRequest);
parentUnitOfWork.AddCommand(new PatchCommandData(failedMessageDocumentId, null, patchRequest));
parentUnitOfWork.AddCommand(new DeleteCommandData(failedMessageRetryDocumentId, null));
return Task.CompletedTask;
}
static string GetUniqueMessageId(MessageContext context)
{
if (context.Headers.TryGetValue("ServiceControl.Retry.UniqueMessageId", out var existingUniqueMessageId))
{
return existingUniqueMessageId;
}
if (!context.Headers.TryGetValue(Headers.MessageId, out var messageId))
{
messageId = context.NativeMessageId;
}
return DeterministicGuid.MakeId(messageId, context.Headers.ProcessingEndpointName()).ToString();
}
ICommandData CreateFailedMessagesPatchCommand(string uniqueMessageId, FailedMessage.ProcessingAttempt processingAttempt,
List<FailedMessage.FailureGroup> groups)
{
var documentId = FailedMessageIdGenerator.MakeDocumentId(uniqueMessageId);
const string ProcessingAttempts = nameof(FailedMessage.ProcessingAttempts);
const string AttemptedAt = nameof(FailedMessage.ProcessingAttempt.AttemptedAt);
//HINT: RavenDB 4.2 removed Lodash utility functions, but supports ECMAScript 5.1 and some 6.0 features like arrow functions and array primitive functions
return new PatchCommandData(documentId, null, new PatchRequest
{
Script = $@"this.{nameof(FailedMessage.Status)} = args.status;
this.{nameof(FailedMessage.FailureGroups)} = args.failureGroups;
var newAttempts = this.{nameof(FailedMessage.ProcessingAttempts)};
//De-duplicate attempts by AttemptedAt value
var duplicateIndex = this.{ProcessingAttempts}.findIndex(a => a.{AttemptedAt} === args.attempt.{AttemptedAt});
if(duplicateIndex < 0){{
newAttempts.push(args.attempt);
}}
//Trim to the latest MaxProcessingAttempts
newAttempts.sort((a, b) => a.{AttemptedAt} > b.{AttemptedAt} ? 1 : -1);
if(newAttempts.length > {MaxProcessingAttempts})
{{
newAttempts = newAttempts.slice(newAttempts.length - {MaxProcessingAttempts}, newAttempts.length);
}}
this.{ProcessingAttempts} = newAttempts;
",
Values = new Dictionary<string, object>
{
{ "status", (int)FailedMessageStatus.Unresolved },
{ "failureGroups", groups },
{ "attempt", processingAttempt }
},
},
patchIfMissing: new PatchRequest
{
Script = $@"this.{nameof(FailedMessage.Status)} = args.status;
this.{nameof(FailedMessage.FailureGroups)} = args.failureGroups;
this.{nameof(FailedMessage.ProcessingAttempts)} = [args.attempt];
this.{nameof(FailedMessage.UniqueMessageId)} = args.uniqueMessageId;
this['@metadata'] = {{
'@collection': '{FailedMessageIdGenerator.CollectionName}',
'Raven-Clr-Type': '{typeof(FailedMessage).AssemblyQualifiedName}'
}}
",
Values = new Dictionary<string, object>
{
{ "status", (int)FailedMessageStatus.Unresolved },
{ "failureGroups", groups },
{ "attempt", processingAttempt },
{ "uniqueMessageId", uniqueMessageId }
}
});
}
void AddStoreBodyCommands(string uniqueMessageId, MessageContext context, string contentType)
{
var documentId = FailedMessageIdGenerator.MakeDocumentId(uniqueMessageId);
var stream = new ReadOnlyStream(context.Body);
var putAttachmentCmd = new PutAttachmentCommandData(documentId, "body", stream, contentType, changeVector: null);
parentUnitOfWork.AddCommand(putAttachmentCmd);
}
static string GetContentType(IReadOnlyDictionary<string, string> headers, string defaultContentType)
=> headers.GetValueOrDefault(Headers.ContentType, defaultContentType);
static int MaxProcessingAttempts = 10;
// large object heap starts above 85000 bytes and not above 85 KB!
internal const int LargeObjectHeapThreshold = 85_000;
static readonly Encoding utf8 = new UTF8Encoding(true, true);
}
}