forked from tompaana/bot-message-routing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AzureTableStorageRoutingDataManager.cs
357 lines (307 loc) · 13.8 KB
/
AzureTableStorageRoutingDataManager.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
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using Underscore.Bot.Models;
using Underscore.Bot.Models.Azure;
using Underscore.Bot.Utils;
namespace Underscore.Bot.MessageRouting.DataStore.Azure
{
/// <summary>
/// Routing data manager that stores the data in Azure Table Storage.
///
/// See IRoutingDataManager and AbstractRoutingDataManager for general documentation of
/// properties and methods.
/// </summary>
[Serializable]
public class AzureTableStorageRoutingDataManager : AbstractRoutingDataManager
{
protected const string TableNameParties = "Parties";
protected const string TableNameConnections = "Connections";
protected const string PartitionKey = "PartitionKey";
protected CloudTable _partiesTable;
protected CloudTable _connectionsTable;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="connectionString">The connection string associated with an Azure Table Storage.</param>
/// <param name="globalTimeProvider">The global time provider for providing the current
/// time for various events such as when a connection is requested.</param>
public AzureTableStorageRoutingDataManager(string connectionString, GlobalTimeProvider globalTimeProvider = null)
: base(globalTimeProvider)
{
if (string.IsNullOrEmpty(connectionString))
{
throw new ArgumentNullException("The connection string cannot be null or empty");
}
_partiesTable = AzureStorageHelper.GetTable(connectionString, TableNameParties);
_connectionsTable = AzureStorageHelper.GetTable(connectionString, TableNameConnections);
MakeSureTablesExist();
}
public override IList<Party> GetUserParties()
{
List<PartyEntity> partyEntities = null;
try
{
partyEntities =
_partiesTable.ExecuteQuery(new TableQuery<PartyEntity>())
.Where(x => x.PartyEntityType == PartyEntityType.User.ToString()).ToList();
}
catch (StorageException e)
{
System.Diagnostics.Debug.WriteLine($"Failed to retrieve the user parties: {e.Message}");
return new List<Party>();
}
return ToPartyList(partyEntities).AsReadOnly();
}
public override IList<Party> GetBotParties()
{
List<PartyEntity> partyEntities = null;
try
{
partyEntities =
_partiesTable.ExecuteQuery(new TableQuery<PartyEntity>())
.Where(x => x.PartyEntityType == PartyEntityType.Bot.ToString()).ToList();
}
catch (StorageException e)
{
System.Diagnostics.Debug.WriteLine($"Failed to retrieve the bot parties: {e.Message}");
return new List<Party>();
}
return ToPartyList(partyEntities).AsReadOnly();
}
public override IList<Party> GetAggregationParties()
{
List<PartyEntity> partyEntities = null;
try
{
partyEntities =
_partiesTable.ExecuteQuery(new TableQuery<PartyEntity>())
.Where(x => x.PartyEntityType == PartyEntityType.Aggregation.ToString()).ToList();
}
catch (StorageException e)
{
System.Diagnostics.Debug.WriteLine($"Failed to retrieve the aggregation parties: {e.Message}");
return new List<Party>();
}
return ToPartyList(partyEntities).AsReadOnly();
}
public override IList<Party> GetPendingRequests()
{
List<PartyEntity> partyEntities = null;
try
{
partyEntities =
_partiesTable.ExecuteQuery(new TableQuery<PartyEntity>())
.Where(x => x.PartyEntityType == PartyEntityType.PendingRequest.ToString()).ToList();
}
catch (StorageException e)
{
System.Diagnostics.Debug.WriteLine($"Failed to retrieve the pending requests: {e.Message}");
return new List<Party>();
}
return ToPartyList(partyEntities).AsReadOnly();
}
public override Dictionary<Party, Party> GetConnectedParties()
{
Dictionary<Party, Party> connectedParties = new Dictionary<Party, Party>();
List<ConnectionEntity> connectionEntities = null;
try
{
connectionEntities =
_connectionsTable.ExecuteQuery(new TableQuery<ConnectionEntity>()).ToList();
}
catch (StorageException e)
{
System.Diagnostics.Debug.WriteLine($"Failed to retrieve the connected parties: {e.Message}");
return connectedParties; // Return empty dictionary
}
foreach (var connectionEntity in connectionEntities)
{
connectedParties.Add(
JsonConvert.DeserializeObject<PartyEntity>(connectionEntity.Owner).ToParty(),
JsonConvert.DeserializeObject<PartyEntity>(connectionEntity.Client).ToParty());
}
return connectedParties;
}
public override void DeleteAll()
{
base.DeleteAll();
try
{
var partyEntities = _partiesTable.ExecuteQuery(new TableQuery<PartyEntity>());
foreach (var partyEntity in partyEntities)
{
AzureStorageHelper.DeleteEntry<PartyEntity>(
_partiesTable, partyEntity.PartitionKey, partyEntity.RowKey);
}
}
catch (StorageException e)
{
System.Diagnostics.Debug.WriteLine($"Failed to delete entries: {e.Message}");
return;
}
var connectionEntities = _connectionsTable.ExecuteQuery(new TableQuery<ConnectionEntity>());
foreach (var connectionEntity in connectionEntities)
{
AzureStorageHelper.DeleteEntry<ConnectionEntity>(
_connectionsTable, connectionEntity.PartitionKey, connectionEntity.RowKey);
}
/*
try
{
_partiesTable.Delete();
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine($"An error occured while trying to delete the parties table: {e.Message}");
}
try
{
_connectionsTable.Delete();
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine($"An error occured while trying to delete the connections table: {e.Message}");
}
*/
}
protected override bool ExecuteAddParty(Party partyToAdd, bool isUser)
{
return AzureStorageHelper.Insert<PartyEntity>(
_partiesTable,
new PartyEntity(partyToAdd, isUser ? PartyEntityType.User : PartyEntityType.Bot));
}
protected override bool ExecuteRemoveParty(Party partyToRemove, bool isUser)
{
return AzureStorageHelper.DeleteEntry<PartyEntity>(
_partiesTable,
PartyEntity.CreatePartitionKey(partyToRemove, isUser ? PartyEntityType.User : PartyEntityType.Bot),
PartyEntity.CreateRowKey(partyToRemove));
}
protected override bool ExecuteAddAggregationParty(Party aggregationPartyToAdd)
{
return AzureStorageHelper.Insert<PartyEntity>(
_partiesTable, new PartyEntity(aggregationPartyToAdd, PartyEntityType.Aggregation));
}
protected override bool ExecuteRemoveAggregationParty(Party aggregationPartyToRemove)
{
var partyEntitiesToRemove = GetPartyEntitiesByPropertyNameAndValue(
PartitionKey,
PartyEntity.CreatePartitionKey(aggregationPartyToRemove, PartyEntityType.Aggregation))
.FirstOrDefault();
return AzureStorageHelper.DeleteEntry<PartyEntity>(
_partiesTable, partyEntitiesToRemove.PartitionKey, partyEntitiesToRemove.RowKey);
}
protected override bool ExecuteAddPendingRequest(Party requestorParty)
{
return AzureStorageHelper.Insert<PartyEntity>(
_partiesTable, new PartyEntity(requestorParty, PartyEntityType.PendingRequest));
}
protected override bool ExecuteRemovePendingRequest(Party requestorParty)
{
return AzureStorageHelper.DeleteEntry<PartyEntity>(
_partiesTable,
PartyEntity.CreatePartitionKey(requestorParty, PartyEntityType.PendingRequest),
PartyEntity.CreateRowKey(requestorParty));
}
protected override bool ExecuteAddConnection(Party conversationOwnerParty, Party conversationClientParty)
{
return AzureStorageHelper.Insert<ConnectionEntity>(_connectionsTable, new ConnectionEntity()
{
PartitionKey = conversationClientParty.ConversationAccount.Id,
RowKey = conversationOwnerParty.ConversationAccount.Id,
Client = JsonConvert.SerializeObject(new PartyEntity(conversationClientParty, PartyEntityType.Client)),
Owner = JsonConvert.SerializeObject(new PartyEntity(conversationOwnerParty, PartyEntityType.Owner))
});
}
protected override bool ExecuteRemoveConnection(Party conversationOwnerParty)
{
Dictionary<Party, Party> connectedParties = GetConnectedParties();
if (connectedParties != null && connectedParties.Remove(conversationOwnerParty))
{
Party conversationClientParty = GetConnectedCounterpart(conversationOwnerParty);
return AzureStorageHelper.DeleteEntry<ConnectionEntity>(
_connectionsTable,
conversationClientParty.ConversationAccount.Id,
conversationOwnerParty.ConversationAccount.Id);
}
return false;
}
/// <summary>
/// Makes sure the required tables exist.
/// </summary>
protected virtual void MakeSureTablesExist()
{
/*
_partiesTable.BeginCreateIfNotExists(OnPartiesTableCreateIfNotExistsFinished, null);
_connectionsTable.BeginCreateIfNotExists(OnConnectionsTableCreateIfNotExistsFinished, null);
*/
try
{
_partiesTable.CreateIfNotExists();
System.Diagnostics.Debug.WriteLine("Parties table created or did already exist");
}
catch (StorageException e)
{
System.Diagnostics.Debug.WriteLine($"Failed to create the parties table (perhaps it already exists): {e.Message}");
}
try
{
_connectionsTable.CreateIfNotExists();
System.Diagnostics.Debug.WriteLine("Connections table created or did already exist");
}
catch (StorageException e)
{
System.Diagnostics.Debug.WriteLine($"Failed to create the connections table (perhaps it already exists): {e.Message}");
}
}
protected virtual void OnPartiesTableCreateIfNotExistsFinished(IAsyncResult result)
{
if (result == null)
{
System.Diagnostics.Debug.WriteLine((result.IsCompleted)
? "Create table operation for parties table completed"
: "Create table operation for parties table did not complete");
}
}
protected virtual void OnConnectionsTableCreateIfNotExistsFinished(IAsyncResult result)
{
if (result == null)
{
System.Diagnostics.Debug.WriteLine((result.IsCompleted)
? "Create table operation for connections table completed"
: "Create table operation for connections table did not complete");
}
}
/// <summary>
/// Resolves the parties in the party (cloud) table by the given property name and value.
/// </summary>
/// <param name="propertyName">The property name for the filter.</param>
/// <param name="value">Party property values to match.</param>
/// <returns>The party entities in the table matching the given property name and value.</returns>
protected virtual IEnumerable<PartyEntity> GetPartyEntitiesByPropertyNameAndValue(string propertyName, string value)
{
TableQuery<PartyEntity> tableQuery =
new TableQuery<PartyEntity>()
.Where(TableQuery.GenerateFilterCondition(propertyName, QueryComparisons.Equal, value));
return _partiesTable.ExecuteQuery(tableQuery);
}
/// <summary>
/// Converts the given entities into a party list.
/// </summary>
/// <param name="partyEntities">The entities to convert.</param>
/// <returns>A newly created list of parties based on the given entities.</returns>
protected virtual List<Party> ToPartyList(IEnumerable<PartyEntity> partyEntities)
{
List<Party> partyList = new List<Party>();
foreach (var partyEntity in partyEntities)
{
partyList.Add(partyEntity.ToParty());
}
return partyList.ToList();
}
}
}