-
Notifications
You must be signed in to change notification settings - Fork 635
/
V8ProjectionStateHandler.cs
260 lines (218 loc) · 7.81 KB
/
V8ProjectionStateHandler.cs
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.Serialization;
using EventStore.Common.Utils;
using EventStore.Projections.Core.Messages;
using EventStore.Projections.Core.Services.Processing;
using EventStore.Projections.Core.v8;
using Newtonsoft.Json.Linq;
using Serilog;
namespace EventStore.Projections.Core.Services.v8 {
using System.Threading;
using Client.PersistentSubscriptions;
public class V8ProjectionStateHandler : IProjectionStateHandler {
private readonly PreludeScript _prelude;
private readonly QueryScript _query;
private List<EmittedEventEnvelope> _emittedEvents;
private CheckpointTag _eventPosition;
private bool _disposed;
private static readonly char[] LinkToSeparator = { '@' };
private static readonly string LinkType = "$>";
private bool _enableContentTypeValidation;
public V8ProjectionStateHandler(
string preludeName, string querySource, Func<string, Tuple<string, string>> getModuleSource,
Action<string, object[]> logger, Action<int, Action> cancelCallbackFactory, bool enableContentTypeValidation) {
var preludeSource = getModuleSource(preludeName);
var prelude = new PreludeScript(preludeSource.Item1, preludeSource.Item2, getModuleSource,
cancelCallbackFactory, logger);
QueryScript query;
try {
query = new QueryScript(prelude, querySource, "POST-BODY");
query.Emit += QueryOnEmit;
} catch {
prelude.Dispose(); // clean up unmanaged resources if failed to create
throw;
}
_prelude = prelude;
_query = query;
_enableContentTypeValidation = enableContentTypeValidation;
}
[DataContract]
public class EmittedEventJsonContract {
[DataMember] public string streamId;
[DataMember] public string eventName;
[DataMember] public bool isJson;
[DataMember] public string body;
[DataMember] public Dictionary<string, JRaw> metadata;
public ExtraMetaData GetExtraMetadata() {
if (metadata == null)
return null;
return new ExtraMetaData(metadata);
}
}
private string GetEventData(ResolvedEvent evnt) {
if (_enableContentTypeValidation) {
return (evnt.IsJson ? evnt.Data : evnt.Data ?? string.Empty)?.Trim();
}
return evnt.Data?.Trim();
}
private void QueryOnEmit(string json) {
EmittedEventJsonContract emittedEvent;
try {
emittedEvent = json.ParseJson<EmittedEventJsonContract>();
} catch (Exception ex) {
throw new ArgumentException("Failed to deserialize emitted event JSON", ex);
}
if (!IsValidEvent(emittedEvent)) {
Log.Warning($"Invalid emitted event was ignored: streamId: [{emittedEvent.streamId}], eventType: [{emittedEvent.eventName}], payload: [{emittedEvent.body}]");
return;
}
if (emittedEvent.eventName.Equals(LinkType) && !IsValidLinkEvent(emittedEvent)) {
Log.Warning($"Invalid emitted link event was ignored: streamId: [{emittedEvent.streamId}], eventType: [{emittedEvent.eventName}], payload: [{emittedEvent.body}]");
return;
}
if (_emittedEvents == null)
_emittedEvents = new List<EmittedEventEnvelope>();
_emittedEvents.Add(
new EmittedEventEnvelope(
new EmittedDataEvent(
emittedEvent.streamId, Guid.NewGuid(), emittedEvent.eventName, emittedEvent.isJson,
emittedEvent.body,
emittedEvent.GetExtraMetadata(), _eventPosition, expectedTag: null)));
}
private QuerySourcesDefinition GetQuerySourcesDefinition() {
CheckDisposed();
var sourcesDefinition = _query.GetSourcesDefintion();
if (sourcesDefinition == null)
throw new InvalidOperationException("Invalid query. No source definition.");
return sourcesDefinition;
}
public void Load(string state) {
CheckDisposed();
_query.SetState(state);
}
public void LoadShared(string state) {
CheckDisposed();
_query.SetSharedState(state);
}
public void Initialize() {
CheckDisposed();
_query.Initialize();
}
public void InitializeShared() {
CheckDisposed();
_query.InitializeShared();
}
public string GetStatePartition(
CheckpointTag eventPosition, string category, ResolvedEvent @event) {
CheckDisposed();
if (@event == null)
throw new ArgumentNullException("event");
if (string.IsNullOrEmpty(@event.EventType)) {
//Nothing to actually process
return null;
}
//Only get the event data if our previous checks passed.
string eventData = GetEventData(@event);
var partition = _query.GetPartition(eventData,
new string[] {
@event.EventStreamId, @event.IsJson ? "1" : "", @event.EventType, category ?? "",
@event.EventSequenceNumber.ToString(CultureInfo.InvariantCulture), @event.Metadata ?? "",
@event.PositionMetadata ?? ""
});
if (partition == "")
return null;
return partition;
}
public bool ProcessEvent(string partition, CheckpointTag eventPosition, string category, ResolvedEvent @event, out string newState, out string newSharedState, out EmittedEventEnvelope[] emittedEvents) {
CheckDisposed();
_eventPosition = eventPosition;
_emittedEvents = null;
Tuple<string, string> newStates = null;
var data = GetEventData(@event);
if (@event == null || data == null || string.IsNullOrEmpty(@event.EventType)) {
newStates = _query.Push(
"",
new string[] { });
} else {
newStates = _query.Push(
data,
new[] {
@event.IsJson ? "1" : "",
@event.EventStreamId,
@event.EventType,
category ?? "",
@event.EventSequenceNumber.ToString(CultureInfo.InvariantCulture),
@event.Metadata ?? "",
@event.PositionMetadata ?? "",
partition,
@event.EventId.ToString()
});
}
newState = newStates.Item1;
newSharedState = newStates.Item2;
emittedEvents = _emittedEvents == null ? null : _emittedEvents.ToArray();
return true;
}
public bool ProcessPartitionCreated(string partition, CheckpointTag createPosition, ResolvedEvent @event,
out EmittedEventEnvelope[] emittedEvents) {
CheckDisposed();
_eventPosition = createPosition;
_emittedEvents = null;
var data = GetEventData(@event);
if (@event == null || data == null || string.IsNullOrEmpty(@event.EventType)) {
emittedEvents = null;
return true;
}
_query.NotifyCreated(
data,
new[] {
@event.IsJson ? "1" : "", @event.EventStreamId, @event.EventType, "",
@event.EventSequenceNumber.ToString(CultureInfo.InvariantCulture), @event.Metadata ?? "",
@event.PositionMetadata ?? "", partition, ""
});
emittedEvents = _emittedEvents == null ? null : _emittedEvents.ToArray();
return true;
}
public bool ProcessPartitionDeleted(string partition, CheckpointTag deletePosition, out string newState) {
CheckDisposed();
_eventPosition = deletePosition;
_emittedEvents = null;
var newStates = _query.NotifyDeleted(
"", // trimming data passed to a JS
new[] {
partition, "" /* isSoftDedleted */
});
newState = newStates;
return true;
}
public string TransformStateToResult() {
CheckDisposed();
var result = _query.TransformStateToResult();
return result;
}
private void CheckDisposed() {
if (_disposed)
throw new InvalidOperationException("Disposed");
}
public void Dispose() {
_disposed = true;
if (_query != null)
_query.Dispose();
if (_prelude != null)
_prelude.Dispose();
}
public IQuerySources GetSourceDefinition() {
return GetQuerySourcesDefinition();
}
private static bool IsValidEvent(EmittedEventJsonContract @event) {
return !(@event.eventName.IsEmptyString() || @event.streamId.IsEmptyString() || @event.isJson && @event.body.IsEmptyString());
}
// This function assumes 'IsValidEvent' was called upfront.
private static bool IsValidLinkEvent(EmittedEventJsonContract @event) {
var parts = @event.body.Split(LinkToSeparator, 2);
return long.TryParse(parts[0], out long _);
}
}
}