-
Notifications
You must be signed in to change notification settings - Fork 64
/
Stream.Operations.cs
463 lines (362 loc) · 16.7 KB
/
Stream.Operations.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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Runtime.ExceptionServices;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos.Table;
namespace Streamstone
{
public sealed partial class Stream
{
class ProvisionOperation
{
readonly Stream stream;
readonly CloudTable table;
public ProvisionOperation(Stream stream)
{
Debug.Assert(stream.IsTransient);
this.stream = stream;
table = stream.Partition.Table;
}
public async Task<Stream> ExecuteAsync()
{
var insert = new Insert(stream);
try
{
await table.ExecuteAsync(insert.Prepare()).ConfigureAwait(false);
}
catch (StorageException e)
{
insert.Handle(e);
}
return insert.Result();
}
class Insert
{
readonly StreamEntity stream;
readonly Partition partition;
public Insert(Stream stream)
{
this.stream = stream.Entity();
partition = stream.Partition;
}
public TableOperation Prepare() => TableOperation.Insert(stream);
internal void Handle(StorageException exception)
{
if (exception.RequestInformation.HttpStatusCode == (int)HttpStatusCode.Conflict)
throw ConcurrencyConflictException.StreamChangedOrExists(partition);
ExceptionDispatchInfo.Capture(exception).Throw();
}
internal Stream Result() => From(partition, stream);
}
}
class WriteOperation
{
const int MaxOperationsPerChunk = 99;
readonly Stream stream;
readonly StreamWriteOptions options;
readonly CloudTable table;
readonly IEnumerable<RecordedEvent> events;
public WriteOperation(Stream stream, StreamWriteOptions options, IEnumerable<EventData> events)
{
this.stream = stream;
this.options = options;
this.events = stream.Record(events);
table = stream.Partition.Table;
}
public async Task<StreamWriteResult> ExecuteAsync()
{
var current = stream;
foreach (var chunk in Chunks())
{
var batch = chunk.ToBatch(current, options);
try
{
await table.ExecuteBatchAsync(batch.Prepare()).ConfigureAwait(false);
}
catch (StorageException e)
{
batch.Handle(e);
}
current = batch.Result();
}
return new StreamWriteResult(current, events.ToArray());
}
IEnumerable<Chunk> Chunks() => Chunk.Split(events).Where(s => !s.IsEmpty);
class Chunk
{
public static IEnumerable<Chunk> Split(IEnumerable<RecordedEvent> events)
{
var current = new Chunk();
foreach (var @event in events)
{
var next = current.Add(@event);
if (next != current)
yield return current;
current = next;
}
yield return current;
}
readonly List<RecordedEvent> events = new List<RecordedEvent>();
int operations;
Chunk()
{}
Chunk(RecordedEvent first) => Accomodate(first);
Chunk Add(RecordedEvent @event)
{
if (@event.Operations > MaxOperationsPerChunk)
throw new InvalidOperationException(
string.Format("{0} include(s) in event {1}:{{{2}}}, plus event entity itself, is over Azure's max batch size limit [{3}]",
@event.IncludedOperations.Length, @event.Version, @event.Id, MaxOperationsPerChunk));
if (!CanAccomodate(@event))
return new Chunk(@event);
Accomodate(@event);
return this;
}
void Accomodate(RecordedEvent @event)
{
operations += @event.Operations;
events.Add(@event);
}
bool CanAccomodate(RecordedEvent @event)
{
return operations + @event.Operations <= MaxOperationsPerChunk;
}
public bool IsEmpty => events.Count == 0;
public Batch ToBatch(Stream stream, StreamWriteOptions options)
{
var entity = stream.Entity();
entity.Version += events.Count;
return new Batch(entity, events, options);
}
}
class Batch
{
readonly List<EntityOperation> operations =
new List<EntityOperation>();
readonly StreamEntity stream;
readonly List<RecordedEvent> events;
readonly StreamWriteOptions options;
readonly Partition partition;
internal Batch(StreamEntity stream, List<RecordedEvent> events, StreamWriteOptions options)
{
this.stream = stream;
this.events = events;
this.options = options;
partition = stream.Partition;
}
internal TableBatchOperation Prepare()
{
WriteStream();
WriteEvents();
WriteIncludes();
return ToBatch();
}
void WriteStream() => operations.Add(stream.Operation());
void WriteEvents() => operations.AddRange(events.SelectMany(e => e.EventOperations));
void WriteIncludes()
{
if (!options.TrackChanges)
{
operations.AddRange(events.SelectMany(x => x.IncludedOperations));
return;
}
var tracker = new EntityChangeTracker();
foreach (var @event in events)
tracker.Record(@event.IncludedOperations);
operations.AddRange(tracker.Compute());
}
TableBatchOperation ToBatch()
{
var result = new TableBatchOperation();
foreach (var each in operations)
result.Add(each);
return result;
}
internal Stream Result()
{
return From(partition, stream);
}
internal void Handle(StorageException exception)
{
if (exception.RequestInformation.HttpStatusCode == (int)HttpStatusCode.PreconditionFailed)
throw ConcurrencyConflictException.StreamChangedOrExists(partition);
if (exception.RequestInformation.HttpStatusCode != (int)HttpStatusCode.Conflict)
ExceptionDispatchInfo.Capture(exception).Throw();
var error = exception.RequestInformation.ExtendedErrorInformation;
if (error.ErrorCode != "EntityAlreadyExists")
throw UnexpectedStorageResponseException.ErrorCodeShouldBeEntityAlreadyExists(error);
var position = ParseConflictingEntityPosition(error);
Debug.Assert(position >= 0 && position < operations.Count);
var conflicting = operations[position].Entity;
if (conflicting == stream)
throw ConcurrencyConflictException.StreamChangedOrExists(partition);
var id = conflicting as EventIdEntity;
if (id != null)
throw new DuplicateEventException(partition, id.Event.Id);
var @event = conflicting as EventEntity;
if (@event != null)
throw ConcurrencyConflictException.EventVersionExists(partition, @event.Version);
var include = operations.Single(x => x.Entity == conflicting);
throw IncludedOperationConflictException.Create(partition, include);
}
static int ParseConflictingEntityPosition(StorageExtendedErrorInformation error)
{
var lines = error.ErrorMessage.Trim().Split('\n');
if (lines.Length != 3)
throw UnexpectedStorageResponseException.ConflictExceptionMessageShouldHaveExactlyThreeLines(error);
var semicolonIndex = lines[0].IndexOf(":", StringComparison.Ordinal);
if (semicolonIndex == -1)
throw UnexpectedStorageResponseException.ConflictExceptionMessageShouldHaveSemicolonOnFirstLine(error);
int position;
if (!int.TryParse(lines[0].Substring(0, semicolonIndex), out position))
throw UnexpectedStorageResponseException.UnableToParseTextBeforeSemicolonToInteger(error);
return position;
}
}
}
class SetPropertiesOperation
{
readonly Stream stream;
readonly CloudTable table;
readonly StreamProperties properties;
public SetPropertiesOperation(Stream stream, StreamProperties properties)
{
this.stream = stream;
this.properties = properties;
table = stream.Partition.Table;
}
public async Task<Stream> ExecuteAsync()
{
var replace = new Replace(stream, properties);
try
{
await table.ExecuteAsync(replace.Prepare()).ConfigureAwait(false);
}
catch (StorageException e)
{
replace.Handle(e);
}
return replace.Result();
}
class Replace
{
readonly StreamEntity stream;
readonly Partition partition;
public Replace(Stream stream, StreamProperties properties)
{
this.stream = stream.Entity();
this.stream.Properties = properties;
partition = stream.Partition;
}
internal TableOperation Prepare()
{
return TableOperation.Replace(stream);
}
internal void Handle(StorageException exception)
{
if (exception.RequestInformation.HttpStatusCode == (int)HttpStatusCode.PreconditionFailed)
throw ConcurrencyConflictException.StreamChanged(partition);
ExceptionDispatchInfo.Capture(exception).Throw();
}
internal Stream Result() => From(partition, stream);
}
}
class OpenStreamOperation
{
readonly Partition partition;
readonly CloudTable table;
public OpenStreamOperation(Partition partition)
{
this.partition = partition;
table = partition.Table;
}
public async Task<StreamOpenResult> ExecuteAsync() =>
Result(await table.ExecuteAsync(Prepare()));
TableOperation Prepare() => TableOperation.Retrieve<StreamEntity>(partition.PartitionKey, partition.StreamRowKey());
StreamOpenResult Result(TableResult result)
{
var entity = result.Result;
return entity != null
? new StreamOpenResult(true, From(partition, (StreamEntity)entity))
: StreamOpenResult.NotFound;
}
}
class ReadOperation<T> where T : class
{
readonly Partition partition;
readonly CloudTable table;
readonly int startVersion;
readonly int sliceSize;
public ReadOperation(Partition partition, int startVersion, int sliceSize)
{
this.partition = partition;
this.startVersion = startVersion;
this.sliceSize = sliceSize;
table = partition.Table;
}
public async Task<StreamSlice<T>> ExecuteAsync(Func<DynamicTableEntity, T> transform)
{
var eventsQuery = ExecuteQueryAsync(EventsQuery());
var streamRowQuery = ExecuteQueryAsync(StreamRowQuery());
await Task.WhenAll(eventsQuery, streamRowQuery);
return Result(await eventsQuery, FindStreamEntity(await streamRowQuery), transform);
}
StreamSlice<T> Result(ICollection<DynamicTableEntity> entities, DynamicTableEntity streamEntity, Func<DynamicTableEntity, T> transform)
{
var stream = BuildStream(streamEntity);
var events = BuildEvents(entities, transform);
return new StreamSlice<T>(stream, events, startVersion, sliceSize);
}
TableQuery<DynamicTableEntity> EventsQuery()
{
var rowKeyStart = partition.EventVersionRowKey(startVersion);
var rowKeyEnd = partition.EventVersionRowKey(startVersion + sliceSize - 1);
var filter = TableQuery.CombineFilters(
TableQuery.GenerateFilterCondition(nameof(DynamicTableEntity.PartitionKey), QueryComparisons.Equal, partition.PartitionKey),
TableOperators.And,
TableQuery.CombineFilters(
TableQuery.GenerateFilterCondition(nameof(DynamicTableEntity.RowKey), QueryComparisons.GreaterThanOrEqual, rowKeyStart),
TableOperators.And,
TableQuery.GenerateFilterCondition(nameof(DynamicTableEntity.RowKey), QueryComparisons.LessThanOrEqual, rowKeyEnd)
)
);
return new TableQuery<DynamicTableEntity>().Where(filter);
}
TableQuery<DynamicTableEntity> StreamRowQuery()
{
var filter = TableQuery.CombineFilters(
TableQuery.GenerateFilterCondition(nameof(DynamicTableEntity.PartitionKey), QueryComparisons.Equal, partition.PartitionKey),
TableOperators.And,
TableQuery.GenerateFilterCondition(nameof(DynamicTableEntity.RowKey), QueryComparisons.Equal, partition.StreamRowKey())
);
return new TableQuery<DynamicTableEntity>().Where(filter);
}
async Task<List<DynamicTableEntity>> ExecuteQueryAsync(TableQuery<DynamicTableEntity> query)
{
var result = new List<DynamicTableEntity>();
TableContinuationToken token = null;
do
{
var segment = await table.ExecuteQuerySegmentedAsync(query, token).ConfigureAwait(false);
token = segment.ContinuationToken;
result.AddRange(segment.Results);
}
while (token != null);
return result;
}
DynamicTableEntity FindStreamEntity(IEnumerable<DynamicTableEntity> entities)
{
var result = entities.SingleOrDefault(x => x.RowKey == partition.StreamRowKey());
if (result == null)
throw new StreamNotFoundException(partition);
return result;
}
Stream BuildStream(DynamicTableEntity entity) => From(partition, StreamEntity.From(entity));
static T[] BuildEvents(IEnumerable<DynamicTableEntity> entities, Func<DynamicTableEntity, T> transform) =>
entities.Select(transform).ToArray();
}
}
}