-
Notifications
You must be signed in to change notification settings - Fork 260
/
Copy pathTripFunctions.cs
324 lines (291 loc) · 13.9 KB
/
TripFunctions.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
using Azure.Messaging.EventGrid;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.EventGrid;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Extensions.SignalRService;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using ServerlessMicroservices.Models;
using ServerlessMicroservices.Shared.Helpers;
using ServerlessMicroservices.Shared.Services;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace ServerlessMicroservices.FunctionApp.Trips
{
public static class TripFunctions
{
[FunctionName("GetTrips")]
public static async Task<IActionResult> GetTrips([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "trips")] HttpRequest req,
ILogger log)
{
log.LogInformation("GetTrips triggered....");
try
{
await Utilities.ValidateToken(req);
var persistenceService = ServiceFactory.GetPersistenceService();
return (ActionResult)new OkObjectResult(await persistenceService.RetrieveTrips());
}
catch (Exception e)
{
var error = $"GetTrips failed: {e.Message}";
log.LogError(error);
if (error.Contains(Constants.SECURITY_VALITION_ERROR))
return new StatusCodeResult(401);
else
return new BadRequestObjectResult(error);
}
}
[FunctionName("GetActiveTrips")]
public static async Task<IActionResult> GetActiveTrips([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "activetrips")] HttpRequest req,
ILogger log)
{
log.LogInformation("GetActiveTrips triggered....");
try
{
await Utilities.ValidateToken(req);
var persistenceService = ServiceFactory.GetPersistenceService();
return (ActionResult)new OkObjectResult(await persistenceService.RetrieveActiveTrips());
}
catch (Exception e)
{
var error = $"GetActiveTrips failed: {e.Message}";
log.LogError(error);
if (error.Contains(Constants.SECURITY_VALITION_ERROR))
return new StatusCodeResult(401);
else
return new BadRequestObjectResult(error);
}
}
[FunctionName("GetTrip")]
public static async Task<IActionResult> GetTrip([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "trips/{code}")] HttpRequest req,
string code,
ILogger log)
{
log.LogInformation("GetTrip triggered....");
try
{
await Utilities.ValidateToken(req);
var persistenceService = ServiceFactory.GetPersistenceService();
return (ActionResult)new OkObjectResult(await persistenceService.RetrieveTrip(code));
}
catch (Exception e)
{
var error = $"GetTrip failed: {e.Message}";
log.LogError(error);
if (error.Contains(Constants.SECURITY_VALITION_ERROR))
return new StatusCodeResult(401);
else
return new BadRequestObjectResult(error);
}
}
[FunctionName("CreateTrip")]
public static async Task<IActionResult> CreateTrip([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "trips")] HttpRequest req,
ILogger log)
{
log.LogInformation("CreateTrip triggered....");
try
{
await Utilities.ValidateToken(req);
string requestBody = new StreamReader(req.Body).ReadToEnd();
TripItem trip = JsonConvert.DeserializeObject<TripItem>(requestBody);
// validate
if (trip.Passenger == null || string.IsNullOrEmpty(trip.Passenger.Code))
throw new Exception("A passenger with a valid code must be attached to the trip!!");
trip.EndDate = null;
var persistenceService = ServiceFactory.GetPersistenceService();
return (ActionResult)new OkObjectResult(await persistenceService.UpsertTrip(trip));
}
catch (Exception e)
{
var error = $"CreateTrip failed: {e.Message}";
log.LogError(error);
if (error.Contains(Constants.SECURITY_VALITION_ERROR))
return new StatusCodeResult(401);
else
return new BadRequestObjectResult(error);
}
}
[FunctionName("AssignTripDriver")]
public static async Task<IActionResult> AssignTripDriver([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "trips/{code}/drivers/{drivercode}")] HttpRequest req,
string code,
string drivercode,
ILogger log)
{
log.LogInformation("AssignTripDriver triggered....");
try
{
await Utilities.ValidateToken(req);
var settingService = ServiceFactory.GetSettingService();
if (!settingService.IsEnqueueToOrchestrators())
{
// Send over to the trip manager
var baseUrl = settingService.GetStartTripManagerOrchestratorBaseUrl();
var key = settingService.GetStartTripManagerOrchestratorApiKey();
if (string.IsNullOrEmpty(baseUrl) || string.IsNullOrEmpty(key))
throw new Exception("Trip manager orchestrator base URL and key must be both provided");
await Utilities.Post<dynamic, dynamic>(null, null, $"{baseUrl}/tripmanagers/{code}/acknowledge/drivers/{drivercode}?code={key}", new Dictionary<string, string>());
}
else
{
await ServiceFactory.GetStorageService().Enqueue(code, drivercode);
}
return (ActionResult)new OkObjectResult("Ok");
}
catch (Exception e)
{
var error = $"AssignTripDriver failed: {e.Message}";
log.LogError(error);
if (error.Contains(Constants.SECURITY_VALITION_ERROR))
return new StatusCodeResult(401);
else
return new BadRequestObjectResult(error);
}
}
/*** SignalR Info or Negotiate Function ****/
[FunctionName("GetSignalRInfo")]
public static async Task<IActionResult> GetSignalRInfo([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "signalrinfo")] HttpRequest req,
[SignalRConnectionInfo(HubName = "trips", UserId = "{headers.x-ms-signalr-userid}")] SignalRConnectionInfo info,
ILogger log)
{
log.LogInformation("GetSignalRInfo triggered....");
try
{
if (info == null)
throw new Exception("SignalR Info is null!");
await Utilities.ValidateToken(req);
return (ActionResult)new OkObjectResult(info);
}
catch (Exception e)
{
var error = $"GetSignalRInfo failed: {e.Message}";
log.LogError(error);
return new BadRequestObjectResult(error);
}
}
/*** Event Grid Listeners ****/
[FunctionName("EVGH_TripExternalizations2SignalR")]
public static async Task ProcessTripExternalizations2SignalR([EventGridTrigger] EventGridEvent eventGridEvent,
[SignalR(HubName = "trips")] IAsyncCollector<SignalRMessage> signalRMessages,
ILogger log)
{
log.LogInformation($"ProcessTripExternalizations2SignalR triggered....EventGridEvent" +
$"\n\tId:{eventGridEvent.Id}" +
$"\n\tTopic:{eventGridEvent.Topic}" +
$"\n\tSubject:{eventGridEvent.Subject}" +
$"\n\tType:{eventGridEvent.EventType}" +
$"\n\tData:{eventGridEvent.Data}");
try
{
TripItem trip = JsonConvert.DeserializeObject<TripItem>(eventGridEvent.Data.ToString());
if (trip == null)
throw new Exception("Trip is null!");
log.LogInformation($"ProcessTripExternalizations2SignalR trip code {trip.Code}");
// Convert the `event subject` to a method to be called on clients
var clientMethod = "tripUpdated";
if (eventGridEvent.Subject == Constants.EVG_SUBJECT_TRIP_DRIVERS_NOTIFIED)
clientMethod = "tripDriversNotified";
else if (eventGridEvent.Subject == Constants.EVG_SUBJECT_TRIP_DRIVER_PICKED)
clientMethod = "tripDriverPicked";
else if (eventGridEvent.Subject == Constants.EVG_SUBJECT_TRIP_STARTING)
clientMethod = "tripStarting";
else if (eventGridEvent.Subject == Constants.EVG_SUBJECT_TRIP_RUNNING)
clientMethod = "tripRunning";
else if (eventGridEvent.Subject == Constants.EVG_SUBJECT_TRIP_COMPLETED)
clientMethod = "tripCompleted";
else if (eventGridEvent.Subject == Constants.EVG_SUBJECT_TRIP_ABORTED)
clientMethod = "tripAborted";
log.LogInformation($"ProcessTripExternalizations2SignalR firing SignalR `{clientMethod}` client method!");
await signalRMessages.AddAsync(new SignalRMessage
{
UserId = trip.Passenger.Code,
Target = clientMethod,
Arguments = new object[] { trip }
});
}
catch (Exception e)
{
var error = $"ProcessTripExternalizations2SignalR failed: {e.Message}";
log.LogError(error);
throw e;
}
}
[FunctionName("EVGH_TripExternalizations2PowerBI")]
public static async Task ProcessTripExternalizations2PowerBI([EventGridTrigger] EventGridEvent eventGridEvent,
ILogger log)
{
log.LogInformation($"ProcessTripExternalizations2PowerBI triggered....EventGridEvent" +
$"\n\tId:{eventGridEvent.Id}" +
$"\n\tTopic:{eventGridEvent.Topic}" +
$"\n\tSubject:{eventGridEvent.Subject}" +
$"\n\tType:{eventGridEvent.EventType}" +
$"\n\tData:{eventGridEvent.Data}");
try
{
TripItem trip = JsonConvert.DeserializeObject<TripItem>(eventGridEvent.Data.ToString());
if (trip == null)
throw new Exception("Trip is null!");
log.LogInformation($"ProcessTripExternalizations2PowerBI trip code {trip.Code}");
if (eventGridEvent.Subject == Constants.EVG_SUBJECT_TRIP_ABORTED ||
eventGridEvent.Subject == Constants.EVG_SUBJECT_TRIP_COMPLETED)
{
var archiveService = ServiceFactory.GetArchiveService();
await archiveService.UpsertTrip(trip);
var powerBIService = ServiceFactory.GetPowerBIService();
await powerBIService.UpsertTrip(trip);
}
}
catch (Exception e)
{
var error = $"ProcessTripExternalizations2PowerBI failed: {e.Message}";
log.LogError(error);
throw e;
}
}
/*** TEST SUPPORT ***/
[FunctionName("StoreTripTestParameters")]
public static async Task<IActionResult> StoreTripTestParameters([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "triptestparameters")] HttpRequest req,
[Blob("trips/testparams.json", FileAccess.Write, Connection = "AzureWebJobsStorage")] Stream outBlob,
ILogger log)
{
log.LogInformation("StoreTripTestParameters triggered....");
try
{
//NOTE: No need for security check as this is used in testing only
var requestBody = new StreamReader(req.Body).ReadToEnd();
byte[] byteArray = Encoding.UTF8.GetBytes(requestBody);
await outBlob.WriteAsync(byteArray, 0, byteArray.Length);
return (ActionResult)new OkObjectResult("Ok");
}
catch (Exception e)
{
var error = $"StoreTripTestParameters failed: {e.Message}";
log.LogError(error);
return new BadRequestObjectResult(error);
}
}
[FunctionName("RetrieveTripTestParameters")]
public static IActionResult RetrieveTripTestParameters([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "triptestparameters")] HttpRequest req,
[Blob("trips/testparams.json", FileAccess.Read, Connection = "AzureWebJobsStorage")] Stream inBlob,
ILogger log)
{
log.LogInformation("RetrieveTripTestParameters triggered....");
try
{
//NOTE: No need for security check as this is used in testing only
StreamReader reader = new StreamReader(inBlob);
return (ActionResult)new OkObjectResult(JsonConvert.DeserializeObject<dynamic>(reader.ReadToEnd()));
}
catch (Exception e)
{
var error = $"RetrieveTripTestParameters failed: {e.Message}";
log.LogError(error);
return new BadRequestObjectResult(error);
}
}
}
}