forked from OrleansContrib/Orleankka
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInfrastructure.cs
194 lines (159 loc) · 5.93 KB
/
Infrastructure.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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Orleankka;
using Orleankka.Meta;
using Orleankka.Cluster;
using Streamstone;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using Newtonsoft.Json;
namespace Example
{
public abstract class CqsActor : Actor
{
public override Task<object> OnReceive(object message)
{
var cmd = message as Command;
if (cmd != null)
return HandleCommand(cmd);
var query = message as Query;
if (query != null)
return HandleQuery(query);
throw new InvalidOperationException("Unknown message type: " + message.GetType());
}
protected abstract Task<object> HandleCommand(Command cmd);
protected abstract Task<object> HandleQuery(Query query);
}
public abstract class EventSourcedActor : CqsActor
{
static readonly JsonSerializerSettings SerializerSettings = new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.None,
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore,
ObjectCreationHandling = ObjectCreationHandling.Replace,
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
Culture = CultureInfo.GetCultureInfo("en-US"),
DateFormatHandling = DateFormatHandling.IsoDateFormat,
TypeNameHandling = TypeNameHandling.None,
FloatParseHandling = FloatParseHandling.Decimal,
Formatting = Formatting.None
};
Stream stream;
public override async Task OnActivate()
{
var partition = new Partition(SS.Table, StreamName());
var existent = Stream.TryOpen(partition);
if (!existent.Found)
{
stream = new Stream(partition);
return;
}
stream = existent.Stream;
StreamSlice<EventEntity> slice;
var nextSliceStart = 1;
do
{
slice = await Stream.ReadAsync<EventEntity>(partition, nextSliceStart);
nextSliceStart = slice.NextEventNumber;
await Replay(slice.Events);
}
while (!slice.IsEndOfStream);
}
string StreamName()
{
return GetType().Name + "-" + Id;
}
async Task Replay(IEnumerable<EventEntity> events)
{
var deserialized = events.Select(DeserializeEvent).ToArray();
await Apply(deserialized);
}
protected override async Task<object> HandleCommand(Command cmd)
{
var events = (await Dispatch<IEnumerable<object>>(cmd)).ToArray();
await Store(events);
await Apply(events);
return events;
}
async Task Apply(IEnumerable<object> events)
{
foreach (var @event in events)
await Dispatch(@event);
}
async Task Store(ICollection<object> events)
{
if (events.Count == 0)
return;
var serialized = events.Select(ToEventData).ToArray();
try
{
var result = await Stream.WriteAsync(stream, serialized);
stream = result.Stream;
}
catch (ConcurrencyConflictException)
{
Console.WriteLine("Concurrency conflict on stream '{0}' detected", StreamName());
Console.WriteLine("Probably, second activation of actor '{0}' has been created", Self);
Console.WriteLine("Deactivating duplicate activation '{0}' ... ", Self);
Activation.DeactivateOnIdle();
throw new InvalidOperationException("Duplicate activation of actor '" + Self + "' detected");
}
}
static object DeserializeEvent(EventEntity @event)
{
var eventType = Type.GetType(@event.Type);
Debug.Assert(eventType != null,
"Couldn't load type '{0}'. Are you missing an assembly reference?", @event.Type);
return JsonConvert.DeserializeObject(@event.Data, eventType, SerializerSettings);
}
static EventData ToEventData(object @event)
{
var id = Guid.NewGuid().ToString("D");
var properties = new EventEntity
{
Id = id,
Type = @event.GetType().FullName,
Data = JsonConvert.SerializeObject(@event, SerializerSettings)
};
return new EventData(EventId.From(id), EventProperties.From(properties));
}
class EventEntity
{
public string Id { get; set; }
public string Type { get; set; }
public string Data { get; set; }
}
protected override Task<object> HandleQuery(Query query)
{
return Dispatch(query);
}
}
public static class SS
{
public static CloudTable Table
{
get; private set;
}
public class Bootstrap : Bootstrapper<Properties>
{
protected override Task Run(IActorSystem system, Properties properties)
{
var client = CloudStorageAccount.Parse(properties.StorageAccount).CreateCloudTableClient();
Table = client.GetTableReference(properties.TableName);
return Task.CompletedTask;
}
}
[Serializable]
public class Properties
{
public string StorageAccount;
public string TableName;
}
}
}