This repository has been archived by the owner on Nov 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathAzureModule.cs
272 lines (239 loc) · 11.1 KB
/
AzureModule.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
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
//
// Microsoft Bot Framework: http://botframework.com
//
// Bot Builder SDK Github:
// https://github.com/Microsoft/BotBuilder
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using Autofac;
using Microsoft.Bot.Builder.Dialogs.Internals;
using Microsoft.Bot.Builder.Internals.Fibers;
using Microsoft.Bot.Builder.Scorables.Internals;
using Microsoft.Bot.Connector;
using Module = Autofac.Module;
namespace Microsoft.Bot.Builder.Azure
{
/// <summary>
/// Autofac module for azure bot components.
/// </summary>
public sealed class AzureModule : Module
{
/// <summary>
/// The key for data store register with the container.
/// </summary>
public static readonly object Key_DataStore = new object();
private readonly Assembly assembly;
/// <summary>
/// Instantiates the azure module.
/// </summary>
/// <param name="assembly">
/// The assembly used by <see cref="BotServiceDelegateSurrogate"/> and
/// <see cref="BotServiceSerializationBinder"/>
/// </param>
public AzureModule(Assembly assembly)
{
SetField.NotNull(out this.assembly, nameof(assembly), assembly);
}
/// <summary>
/// Registers dependencies with the <paramref name="builder"/>.
/// </summary>
/// <param name="builder"> The container builder.</param>
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<ConnectorStore>()
.AsSelf()
.InstancePerLifetimeScope();
// if application settings indicate that bot should use the table storage,
// TableBotDataStore will be registered as underlying storage
// otherwise bot connector state service will be used.
if (ShouldUseTableStorage())
{
builder.Register(c => MakeTableBotDataStore())
.Keyed<IBotDataStore<BotData>>(Key_DataStore)
.AsSelf()
.SingleInstance();
}
else if (ShouldUseTableStorage2())
{
builder.Register(c => MakeTableBotDataStore2())
.Keyed<IBotDataStore<BotData>>(Key_DataStore)
.AsSelf()
.SingleInstance();
}
else if (ShouldUseCosmosDb())
{
builder.Register(c => MakeCosmosDbBotDataStore())
.Keyed<IBotDataStore<BotData>>(Key_DataStore)
.AsSelf()
.SingleInstance();
}
else if (ShouldUseSqlServer())
{
SqlBotDataContext.AssertDatabaseReady();
builder.Register(c => MakeSqlBotDataStore())
.Keyed<IBotDataStore<BotData>>(Key_DataStore)
.AsSelf()
.SingleInstance();
}
else
{
builder.Register(c => new ConnectorStore(c.Resolve<IStateClient>()))
.Keyed<IBotDataStore<BotData>>(Key_DataStore)
.AsSelf()
.InstancePerLifetimeScope();
}
// register the data store with caching data store
// and set the consistency policy to be "Last write wins".
builder.Register(c => new CachingBotDataStore(c.ResolveKeyed<IBotDataStore<BotData>>(Key_DataStore),
CachingBotDataStoreConsistencyPolicy.LastWriteWins))
.As<IBotDataStore<BotData>>()
.AsSelf()
.InstancePerLifetimeScope();
// register the appropriate StateClient based on the state api url.
builder.Register(c =>
{
var activity = c.Resolve<IActivity>();
if (activity.ChannelId == "emulator")
{
// for emulator we should use serviceUri of the emulator for storage
return new StateClient(new Uri(activity.ServiceUrl));
}
MicrosoftAppCredentials.TrustServiceUrl(BotService.stateApi.Value, DateTime.MaxValue);
return new StateClient(new Uri(BotService.stateApi.Value));
})
.As<IStateClient>()
.InstancePerLifetimeScope();
// register the bot service serialization binder for type mapping to current assembly
builder.Register(c => new BotServiceSerializationBinder(assembly))
.AsSelf()
.As<SerializationBinder>()
.InstancePerLifetimeScope();
// register the Delegate surrogate provide to map delegate to current assembly during deserialization
builder
.Register(c => new BotServiceDelegateSurrogate(assembly))
.AsSelf()
.InstancePerLifetimeScope();
// extend surrogate providers with bot service delegate surrogate provider and register the surrogate selector
builder
.Register(c =>
{
var providers = c.ResolveKeyed<IEnumerable<Serialization.ISurrogateProvider>>(FiberModule.Key_SurrogateProvider).ToList();
// need to add the latest delegate surrogate to make sure that surrogate selector
// can deal with latest assembly
providers.Add(c.Resolve<BotServiceDelegateSurrogate>());
return new Serialization.SurrogateSelector(providers);
})
.As<ISurrogateSelector>()
.InstancePerLifetimeScope();
// register binary formatter used for binary serialization operation
builder
.Register((c, p) => new BinaryFormatter(c.Resolve<ISurrogateSelector>(), new StreamingContext(StreamingContextStates.All, c.Resolve<IResolver>(p)))
{
AssemblyFormat = FormatterAssemblyStyle.Simple,
Binder = c.Resolve<SerializationBinder>()
})
.As<IFormatter>()
.InstancePerLifetimeScope();
}
private bool ShouldUseTableStorage()
{
bool shouldUseTableStorage = false;
var useTableStore = Utils.GetAppSetting(AppSettingKeys.UseTableStorageForConversationState);
return bool.TryParse(useTableStore, out shouldUseTableStorage) && shouldUseTableStorage;
}
private bool ShouldUseTableStorage2()
{
bool shouldUseTableStorage = false;
var useTableStore = Utils.GetAppSetting(AppSettingKeys.UseTableStorage2ForConversationState);
return bool.TryParse(useTableStore, out shouldUseTableStorage) && shouldUseTableStorage;
}
private bool ShouldUseCosmosDb()
{
bool shouldUseCosmosDb = false;
var useCosmosDb = Utils.GetAppSetting(AppSettingKeys.UseCosmosDbForConversationState);
return bool.TryParse(useCosmosDb, out shouldUseCosmosDb) && shouldUseCosmosDb;
}
private bool ShouldUseSqlServer()
{
bool shouldUseSqlServer = false;
var useSqlServer = Utils.GetAppSetting(AppSettingKeys.UseSqlServerForConversationState);
return bool.TryParse(useSqlServer, out shouldUseSqlServer) && shouldUseSqlServer;
}
private DocumentDbBotDataStore MakeCosmosDbBotDataStore()
{
var endpoint = Utils.GetAppSetting(AppSettingKeys.CosmosDbEndpoint);
var key = Utils.GetAppSetting(AppSettingKeys.CosmosDbKey);
if (string.IsNullOrEmpty(endpoint))
{
throw new ArgumentException("Endpoint for cosmos db is not set in application settings");
}
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("Key for cosmos db is not set in application settings");
}
return new DocumentDbBotDataStore(new Uri(endpoint), key);
}
private TableBotDataStore MakeTableBotDataStore()
{
var connectionString = Utils.GetAppSetting(AppSettingKeys.TableStorageConnectionString);
if (!string.IsNullOrEmpty(connectionString))
{
return new TableBotDataStore(connectionString);
}
// no connection string in application settings but should use table storage flag is set.
throw new ArgumentException("Connection string for table storage is not set in application setting.");
}
private TableBotDataStore2 MakeTableBotDataStore2()
{
var connectionString = Utils.GetAppSetting(AppSettingKeys.TableStorageConnectionString);
if (!string.IsNullOrEmpty(connectionString))
{
return new TableBotDataStore2(connectionString);
}
// no connection string in application settings but should use table storage flag is set.
throw new ArgumentException("Connection string for table storage is not set in application setting.");
}
private SqlBotDataStore MakeSqlBotDataStore()
{
var connectionString = Utils.GetAppSetting(AppSettingKeys.SqlServerConnectionString);
if (!string.IsNullOrEmpty(connectionString))
{
return new SqlBotDataStore(connectionString);
}
// no connection string in application settings but should use sql server flag is set.
throw new ArgumentException("Connection string for sql server is not set in application settings.");
}
}
}