aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/FSE/Tango.FSE.BL/DataResolver.cs
blob: 9504ae0af42809792e5aecdd7ab63bc89949be25 (plain)
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.Core;
using Tango.Core.DI;
using Tango.FSE.BL.Connectivity;
using Tango.Logging;

namespace Tango.FSE.BL
{
    /// <summary>
    /// Represents a cascading/fallback data retrieval mechanism.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <seealso cref="Tango.Core.ExtendedObject" />
    public class DataResolver<T> : ExtendedObject where T : class
    {
        private static object diskLock = new object();
        private static IConnectivityProvider _connectivity;
        private Func<DataResolverContext, T> _onlineAction;
        private Func<DataResolverContext, T> _webAction;
        private Func<DataResolverContext, T> _diskCacheAction;
        private Func<DataResolverContext, T> _memoryCacheAction;
        private Action<Exception> _onError;
        private Action<T> _onComplete;
        private List<DataResolverNode> _nodes;
        private bool _throwOnError;
        private String _callingName;
        private bool _enableLogs = true;

        /// <summary>
        /// Prevents a default instance of the <see cref="DataResolver{T}"/> class from being created.
        /// </summary>
        private DataResolver()
        {
            if (_connectivity == null)
            {
                _connectivity = TangoIOC.Default.GetInstance<IConnectivityProvider>();
            }

            _nodes = new List<DataResolverNode>() { DataResolverNode.Online };
            _throwOnError = true;
        }

        /// <summary>
        /// Executes this data resolver.
        /// </summary>
        /// <returns></returns>
        /// <exception cref="System.InvalidOperationException">Could not execute data resolver with zero nodes.</exception>
        public T Execute()
        {
            if (_enableLogs) LogManager.Log($"Executing data resolver for {_callingName}...");

            T result = null;

            var nodes = _nodes.Distinct().ToList();

            if (nodes.Count == 0)
            {
                throw new InvalidOperationException("Could not execute data resolver with zero nodes.");
            }

            DataResolverContext context = new DataResolverContext();

            foreach (var node in nodes)
            {
                String fallingBackText = String.Empty;

                if (nodes.IndexOf(node) < nodes.Count - 1)
                {
                    fallingBackText = $" Falling back to {nodes[nodes.IndexOf(node) + 1]}...";
                }

                if (node == DataResolverNode.Web)
                {
                    try
                    {
                        if (_enableLogs) LogManager.Log($"Trying {_callingName} via web...");
                        result = ExecuteWebAction(context);
                        break;
                    }
                    catch (Exception ex)
                    {
                        if (_enableLogs) LogManager.Log($"{_callingName} via web failed with exception: {ex.FlattenMessage()}{fallingBackText}", LogCategory.Warning);
                        context.LastError = ex;
                    }
                }
                else if (node == DataResolverNode.Online)
                {
                    try
                    {
                        if (_enableLogs) LogManager.Log($"Trying {_callingName} via online...");
                        result = ExecuteOnlineAction(context);
                        break;
                    }
                    catch (Exception ex)
                    {
                        if (_enableLogs) LogManager.Log($"{_callingName} via online failed with exception: {ex.FlattenMessage()}{fallingBackText}", LogCategory.Warning);
                        context.LastError = ex;
                    }
                }
                else if (node == DataResolverNode.DiskCache)
                {
                    try
                    {
                        if (_enableLogs) LogManager.Log($"Trying {_callingName} via disk cache...");
                        result = _diskCacheAction.Invoke(context);
                        break;
                    }
                    catch (Exception ex)
                    {
                        if (_enableLogs) LogManager.Log($"{_callingName} via disk cache failed with exception: {ex.FlattenMessage()}{fallingBackText}");
                        context.LastError = ex;
                    }
                }
                else if (node == DataResolverNode.InMemoryCache)
                {
                    try
                    {
                        if (_enableLogs) LogManager.Log($"Trying {_callingName} via in-memory cache...");
                        result = _memoryCacheAction.Invoke(context);
                        break;
                    }
                    catch (Exception ex)
                    {
                        if (_enableLogs) LogManager.Log($"{_callingName} via in-memory cache failed with exception: {ex.FlattenMessage()}{fallingBackText}");
                        context.LastError = ex;
                    }
                }

                if (context.Aborted)
                {
                    if (_enableLogs) LogManager.Log($"{_callingName} aborted.");
                    break;
                }
            }

            if (result != null)
            {
                if (_enableLogs) LogManager.Log($"{_callingName} completed successfully.");
                _onComplete?.Invoke(result);
                return result;
            }

            if (context.LastError == null)
            {
                context.LastError = new InvalidOperationException("No nodes were run successfully but could not retrieve the last error.");
            }

            if (_enableLogs) LogManager.Log(context.LastError, $"{_callingName} failed.");

            _onError?.Invoke(context.LastError);

            if (_throwOnError)
            {
                throw context.LastError;
            }
            else
            {
                return null;
            }
        }

        private T ExecuteOnlineAction(DataResolverContext context)
        {
            if (!_connectivity.CheckOnline())
            {
                throw new InternetConnectionException();
            }

            return _onlineAction.Invoke(context);
        }

        private T ExecuteWebAction(DataResolverContext context)
        {
            if (!_connectivity.CheckOnline())
            {
                throw new InternetConnectionException();
            }

            return _webAction.Invoke(context);
        }

        #region Context

        /// <summary>
        /// Represents a data resolver node context.
        /// </summary>
        /// <seealso cref="Tango.Core.ExtendedObject" />
        public class DataResolverContext
        {
            internal bool Aborted { get; set; }

            /// <summary>
            /// Gets the last error, or maybe the reason that the current node is running.
            /// </summary>
            public Exception LastError { get; internal set; }

            internal DataResolverContext()
            {

            }

            /// <summary>
            /// Aborts the entire data resolver.
            /// </summary>
            public void AbortCascade()
            {
                Aborted = true;
            }
        }

        #endregion

        #region Builder

        /// <summary>
        /// Build a <see cref="DataResolver{T}"/> instance.
        /// </summary>
        /// <seealso cref="Tango.Core.ExtendedObject" />
        public class Builder
        {
            private DataResolver<T> _resolver;

            /// <summary>
            /// Prevents a default instance of the <see cref="Builder"/> class from being created.
            /// </summary>
            private Builder()
            {
                _resolver = new DataResolver<T>();
            }

            /// <summary>
            /// Creates a new builder instance.
            /// </summary>
            /// <returns></returns>
            public static Builder New()
            {
                var method = new StackTrace().GetFrame(1).GetMethod();
                var cls = method.ReflectedType.Name;

                var builder = new Builder();
                builder._resolver._callingName = $"'{cls}.{method.Name}'";

                return builder;
            }

            /// <summary>
            /// Specify the method for the online node.
            /// </summary>
            /// <param name="func">The method.</param>
            /// <returns></returns>
            public Builder Online(Func<DataResolverContext, T> func)
            {
                _resolver._onlineAction = func;
                return this;
            }

            /// <summary>
            /// Specify the method for the web client node.
            /// </summary>
            /// <param name="func">The method.</param>
            /// <returns></returns>
            public Builder Web(Func<DataResolverContext, T> func)
            {
                _resolver._webAction = func;
                return this;
            }

            /// <summary>
            /// Specify the method for the disk cache node.
            /// </summary>
            /// <param name="func">The method.</param>
            /// <returns></returns>
            public Builder DiskCache(Func<DataResolverContext, T> func)
            {
                _resolver._diskCacheAction = func;
                return this;
            }

            /// <summary>
            /// Specify the method for the in-memory node.
            /// </summary>
            /// <param name="func">The method.</param>
            /// <returns></returns>
            public Builder InMemoryCache(Func<DataResolverContext, T> func)
            {
                _resolver._memoryCacheAction = func;
                return this;
            }

            /// <summary>
            /// Configure the node cascade priority.
            /// </summary>
            /// <param name="nodes">The nodes.</param>
            /// <returns></returns>
            public Builder ConfigureCascade(params DataResolverNode[] nodes)
            {
                _resolver._nodes = nodes.ToList();
                return this;
            }

            /// <summary>
            /// Called when all nodes have failed.
            /// </summary>
            /// <param name="onError">The on error.</param>
            /// <returns></returns>
            public Builder OnError(Action<Exception> onError)
            {
                _resolver._onError = onError;
                return this;
            }

            /// <summary>
            /// Called when one of the nodes completed successful.
            /// </summary>
            /// <param name="onComplete">The on complete.</param>
            /// <returns></returns>
            public Builder OnComplete(Action<T> onComplete)
            {
                _resolver._onComplete = onComplete;
                return this;
            }

            /// <summary>
            /// Specify whether to throw the last exception when all the nodes have failed.
            /// </summary>
            /// <param name="throwOnError">if set to <c>true</c> [throw on error].</param>
            /// <returns></returns>
            public Builder ThrowOnError(bool throwOnError)
            {
                _resolver._throwOnError = throwOnError;
                return this;
            }

            /// <summary>
            /// Specify whether to enable data resolver logging.
            /// </summary>
            /// <param name="enableLogs">if set to enables logging.</param>
            /// <returns></returns>
            public Builder EnableLogs(bool enableLogs)
            {
                _resolver._enableLogs = enableLogs;
                return this;
            }

            /// <summary>
            /// Specify a custom name for the calling service when logs are enabled.
            /// </summary>
            /// <param name="callingName">Name of the calling service.</param>
            /// <returns></returns>
            public Builder WithLogsCallingName(String callingName)
            {
                var method = new StackTrace().GetFrame(1).GetMethod();
                _resolver._callingName = $"'{callingName}.{method.Name}'";
                return this;
            }

            /// <summary>
            /// Builds this <see cref="DataResolver{T}"/> instance.
            /// </summary>
            /// <returns></returns>
            public DataResolver<T> Build()
            {
                return _resolver;
            }

            /// <summary>
            /// Builds the executes the <see cref="DataResolver{T}"/> instance.
            /// </summary>
            /// <returns></returns>
            public T BuildExecute()
            {
                return Build().Execute();
            }

            /// <summary>
            /// Builds the executes the <see cref="DataResolver{T}"/> instance asynchronous.
            /// </summary>
            /// <returns></returns>
            public Task<T> BuildExecuteAsync()
            {
                return Task.Factory.StartNew(() => Build().Execute());
            }
        }

        #endregion
    }
}