-
Notifications
You must be signed in to change notification settings - Fork 2
/
Services.cs
165 lines (148 loc) · 8.56 KB
/
Services.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
#region Related components
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using WampSharp.V2.Client;
using net.vieapps.Components.Utility;
using net.vieapps.Components.Security;
#endregion
namespace net.vieapps.Services
{
public static partial class Global
{
/// <summary>
/// Calls a service
/// </summary>
/// <param name="context"></param>
/// <param name="requestInfo">The requesting information</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <param name="logger">The local logger</param>
/// <param name="objectName">The name of object to write into log</param>
/// <param name="onStart">The action to run when start</param>
/// <param name="onSuccess">The action to run when success</param>
/// <param name="onError">The action to run when got an error</param>
/// <returns>A <see cref="JToken">JSON</see> object that presents the results of the business service</returns>
public static async Task<JToken> CallServiceAsync(this HttpContext context, RequestInfo requestInfo, CancellationToken cancellationToken = default, ILogger logger = null, string objectName = null, Action<RequestInfo> onStart = null, Action<RequestInfo, JToken> onSuccess = null, Action<RequestInfo, Exception> onError = null)
{
Exception exception = null;
var overallWatch = Stopwatch.StartNew();
var callingWatch = Stopwatch.StartNew();
var developerID = requestInfo.Session?.DeveloperID ?? context.GetSession(requestInfo.Session?.SessionID, requestInfo.Session?.User)?.DeveloperID;
var appID = requestInfo.Session?.AppID ?? context.GetSession(requestInfo.Session?.SessionID, requestInfo.Session?.User)?.AppID;
try
{
if (Global.IsDebugResultsEnabled)
await context.WriteLogsAsync(developerID, appID, logger ?? Global.Logger, objectName ?? $"Http.{requestInfo.ServiceName}", new List<string> { $"Start call service {requestInfo.Verb} {requestInfo.GetURI()} - {requestInfo.Session.AppName} ({requestInfo.Session.AppMode.ToLower()} app) - {requestInfo.Session.AppPlatform} @ {requestInfo.Session.IP}" }, null, Global.ServiceName, LogLevel.Information, requestInfo.CorrelationID).ConfigureAwait(false);
onStart?.Invoke(requestInfo);
callingWatch = Stopwatch.StartNew();
var service = Router.GetService(requestInfo.ServiceName);
var json = service != null ? await service.ProcessRequestAsync(requestInfo, cancellationToken).ConfigureAwait(false) : null;
callingWatch.Stop();
onSuccess?.Invoke(requestInfo, json);
// TO DO: track counter of success
// ...
if (Global.IsDebugResultsEnabled)
await context.WriteLogsAsync(developerID, appID, logger ?? Global.Logger, objectName ?? $"Http.{requestInfo.ServiceName}", new List<string> { "Call service successful" + "\r\n" +
$"- Request: {requestInfo.ToString(Global.IsDebugLogEnabled ? Formatting.Indented : Formatting.None)}" + "\r\n" +
$"- Response: {json?.ToString(Global.IsDebugLogEnabled ? Formatting.Indented : Formatting.None)}" }
, null, Global.ServiceName, LogLevel.Information, requestInfo.CorrelationID).ConfigureAwait(false);
return json;
}
catch (WampSessionNotEstablishedException)
{
await Task.Delay(UtilityService.GetRandomNumber(567, 789), cancellationToken).ConfigureAwait(false);
Router.IncomingChannel?.ReOpen(cancellationToken);
Router.OutgoingChannel?.ReOpen(cancellationToken);
await Task.Delay(UtilityService.GetRandomNumber(567, 789), cancellationToken).ConfigureAwait(false);
try
{
var service = Router.GetService(requestInfo.ServiceName);
var json = service != null ? await service.ProcessRequestAsync(requestInfo, cancellationToken).ConfigureAwait(false) : null;
callingWatch.Stop();
onSuccess?.Invoke(requestInfo, json);
// TO DO: track counter of success
// ...
if (Global.IsDebugResultsEnabled)
await context.WriteLogsAsync(developerID, appID, logger ?? Global.Logger, objectName ?? $"Http.{requestInfo.ServiceName}", new List<string> { "Re-call service successful" + "\r\n" +
$"- Request: {requestInfo.ToString(Global.IsDebugLogEnabled ? Formatting.Indented : Formatting.None)}" + "\r\n" +
$"- Response: {json?.ToString(Global.IsDebugLogEnabled ? Formatting.Indented : Formatting.None)}" }
, null, Global.ServiceName, LogLevel.Information, requestInfo.CorrelationID).ConfigureAwait(false);
return json;
}
catch (Exception)
{
throw;
}
}
catch (Exception ex)
{
callingWatch.Stop();
exception = ex;
// TO DO: track counter of error
// ...
onError?.Invoke(requestInfo, ex);
throw;
}
finally
{
overallWatch.Stop();
// TO DO: track counter of average times
// ...
if (Global.IsDebugResultsEnabled)
await context.WriteLogsAsync(developerID, appID, logger ?? Global.Logger, objectName ?? $"Http.{requestInfo.ServiceName}", new List<string> { $"Call service finished in {callingWatch.GetElapsedTimes()} - Overall: {overallWatch.GetElapsedTimes()}" }, exception, Global.ServiceName, exception == null ? LogLevel.Information : LogLevel.Error, requestInfo.CorrelationID, exception == null ? null : $"Request: {requestInfo.ToString(Global.IsDebugLogEnabled ? Formatting.Indented : Formatting.None)}").ConfigureAwait(false);
}
}
/// <summary>
/// Calls a service
/// </summary>
/// <param name="requestInfo">The requesting information</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <param name="logger">The local logger</param>
/// <param name="objectName">The name of object to write into log</param>
/// <param name="onStart">The action to run when start</param>
/// <param name="onSuccess">The action to run when success</param>
/// <param name="onError">The action to run when got an error</param>
/// <returns></returns>
public static Task<JToken> CallServiceAsync(RequestInfo requestInfo, CancellationToken cancellationToken = default, ILogger logger = null, string objectName = null, Action<RequestInfo> onStart = null, Action<RequestInfo, JToken> onSuccess = null, Action<RequestInfo, Exception> onError = null)
=> Global.CallServiceAsync(Global.CurrentHttpContext, requestInfo, cancellationToken, logger, objectName, onStart, onSuccess, onError);
/// <summary>
/// Calls a service
/// </summary>
/// <param name="context"></param>
/// <param name="serviceName"></param>
/// <param name="objectName"></param>
/// <param name="verb"></param>
/// <param name="query"></param>
/// <param name="extra"></param>
/// <param name="logger">The local logger</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <param name="onStart"></param>
/// <param name="onSuccess"></param>
/// <param name="onError"></param>
/// <returns></returns>
public static Task<JToken> CallServiceAsync(this HttpContext context, string serviceName, string objectName, string verb, Dictionary<string, string> query, Dictionary<string, string> extra = null, ILogger logger = null, CancellationToken cancellationToken = default, Action<RequestInfo> onStart = null, Action<RequestInfo, JToken> onSuccess = null, Action<RequestInfo, Exception> onError = null)
=> context.CallServiceAsync(new RequestInfo(context.GetSession(UtilityService.NewUUID, context.User?.Identity as UserIdentity), serviceName, objectName, verb, query, null, null, extra, context.GetCorrelationID()), cancellationToken, logger, null, onStart, onSuccess, onError);
/// <summary>
/// Calls a service
/// </summary>
/// <param name="serviceName"></param>
/// <param name="objectName"></param>
/// <param name="verb"></param>
/// <param name="query"></param>
/// <param name="extra"></param>
/// <param name="logger">The local logger</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <param name="onStart"></param>
/// <param name="onSuccess"></param>
/// <param name="onError"></param>
/// <returns></returns>
public static Task<JToken> CallServiceAsync(string serviceName, string objectName, string verb, Dictionary<string, string> query, Dictionary<string, string> extra = null, ILogger logger = null, CancellationToken cancellationToken = default, Action<RequestInfo> onStart = null, Action<RequestInfo, JToken> onSuccess = null, Action<RequestInfo, Exception> onError = null)
=> Global.CallServiceAsync(Global.CurrentHttpContext, serviceName, objectName, verb, query, extra, logger, cancellationToken, onStart, onSuccess, onError);
}
}