-
Notifications
You must be signed in to change notification settings - Fork 229
Expand file tree
/
Copy pathProxyController.cs
More file actions
709 lines (604 loc) · 31.3 KB
/
Copy pathProxyController.cs
File metadata and controls
709 lines (604 loc) · 31.3 KB
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using CodeProject.AI.SDK.API;
using CodeProject.AI.SDK.Common;
using CodeProject.AI.SDK.Utils;
using CodeProject.AI.Server.Backend;
using CodeProject.AI.Server.Modules;
using CodeProject.AI.Server.Mesh;
namespace CodeProject.AI.Server.Controllers
{
// ------------------------------------------------------------------------------
// When a backend analysis module starts it will register itself with the main
// Server. It does this by Posting as Register request to the Server which
// - provides the end part of url for the request
// - the name of the queue that the request will be sent to.
// - the command string that will be associated with the payload sent to the queue.
//
// To initiate an AI operation, the client will post a payload to the server
// This is accomplished by
// - getting the url ending.
// - using this to get the queue name and command name
// - sending the above, plus a payload, to the queue
// - await the response
// - return the response to the caller.
// ------------------------------------------------------------------------------
/// <summary>
/// This controller just passes the payload to the backend queues for processing.
/// </summary>
// TODO: add Version to the RouteMaps or remove the [Route("v1")] from the controller
// and include the v1 in the route
[Route("v1")]
[ApiController]
public class ProxyController : ControllerBase
{
private static HttpClient _httpClient = new ()
{
Timeout = TimeSpan.FromSeconds(30)
};
private const string CPAI_Forwarded_Header = "X-CPAI-Forwarded";
private readonly CommandDispatcher _dispatcher;
private readonly BackendRouteMap _routeMap;
private readonly ModuleCollection _installedModules;
private readonly TriggersConfig _triggersConfig;
private readonly TriggerTaskRunner _commandRunner;
private readonly MeshManager _meshManager;
private readonly ModuleProcessServices _moduleProcessService;
private readonly ILogger<ProxyController> _logger;
private bool _verbose = false;
/// <summary>
/// Initializes a new instance of the ProxyController class.
/// </summary>
/// <param name="dispatcher">The Command Dispatcher instance.</param>
/// <param name="routeMap">The Route Manager</param>
/// <param name="ModuleCollectionOptions">Contains the Collection of modules</param>
/// <param name="triggersConfig">Contains the triggers</param>
/// <param name="commandRunner">The command runner</param>
/// <param name="meshManager">The mesh manager</param>
/// <param name="moduleProcessService">The module process service</param>
/// <param name="logger">The logger</param>
public ProxyController(CommandDispatcher dispatcher,
BackendRouteMap routeMap,
IOptions<ModuleCollection> ModuleCollectionOptions,
IOptions<TriggersConfig> triggersConfig,
TriggerTaskRunner commandRunner,
MeshManager meshManager,
ModuleProcessServices moduleProcessService,
ILogger<ProxyController> logger)
{
_dispatcher = dispatcher;
_routeMap = routeMap;
_installedModules = ModuleCollectionOptions.Value;
_triggersConfig = triggersConfig.Value;
_commandRunner = commandRunner;
_meshManager = meshManager;
_moduleProcessService = moduleProcessService;
_logger = logger;
}
/// <summary>
/// Passes the payload to the queue for processing.
/// </summary>
/// <param name="pathSuffix">The path for this request without the "v1". This will be in the
/// form "category/module[/command]". eg "image/alpr" or "vision/custom/modelName".</param>
/// <returns>The result of the command, or error.</returns>
[HttpPost]
[Route("{**pathSuffix}")]
public async Task<IActionResult> Post(string pathSuffix)
{
if (_verbose)
Debug.WriteLine("TRACE: Received call to " + pathSuffix);
// check if this is a forwarded request and if so run locally.
Microsoft.Extensions.Primitives.StringValues forwardedHeader;
bool isForwardedRequest = Request.Headers.TryGetValue(CPAI_Forwarded_Header,
out forwardedHeader)
&& forwardedHeader == "true";
if (isForwardedRequest && !_meshManager.AcceptForwardedRequests)
return BadRequest("This server does not accept forwarded requests.");
object? response = null;
if (!isForwardedRequest && _meshManager.AllowRequestForwarding)
{
// Find the 'best' server to use for this request.
MeshServerRoutingEntry? server = _meshManager.SelectServer(pathSuffix);
// If a remote server was selected, forward the request to that server.
if (server is not null && !server.IsLocalServer)
{
if (_verbose)
Debug.WriteLine("TRACE: Forwarding to server " + server);
response = await DispatchRemoteRequest(pathSuffix, server).ConfigureAwait(false);
// return await DispatchRemoteRequest(pathSuffix, server).ConfigureAwait(false);
}
}
// we have not forwarded, so this is a local request, do it the normal way.
if (response is null && _routeMap.TryGetValue(pathSuffix, "POST", out RouteQueueInfo? routeInfo))
{
if (_verbose)
Debug.WriteLine("TRACE: Processing locally");
response = await DispatchLocalRequest(pathSuffix, routeInfo!).ConfigureAwait(false);
// return await DispatchLocalRequest(pathSuffix, routeInfo!).ConfigureAwait(false);
}
else if (_verbose)
Debug.WriteLine("ERROR: Unable to process: no suitable mesh server or local route found");
if (response is null)
{
return NotFound();
}
else if (response is string responseString)
{
return new ObjectResult(responseString);
}
else if (response is JsonObject responseObject)
{
// Add common reporting properties
responseObject["timestampUTC"] = DateTime.UtcNow.ToString("R");
// Or to create a form that show DateKind, use
// responseObject["timestampUTC"] = DateTime.Now.ToUniversalTime().ToString("O");
// Report to debug
// long timeMs = responseObject["analysisRoundTripMs"]?.GetValue<long>() ?? 0;
// Debug.WriteLine($"INFO: {pathSuffix} call processed in {timeMs}ms");
responseString = JsonSerializer.Serialize(responseObject);
return new ContentResult
{
Content = responseString,
ContentType = "application/json",
StatusCode = StatusCodes.Status200OK
};
}
else
{
return new ObjectResult(response);
}
}
private async Task<IActionResult> SendCommandToModuleAsync(string moduleId, string commandId, string command)
{
if (string.IsNullOrEmpty(moduleId) || string.IsNullOrEmpty(commandId))
return BadRequest("ModuleId and CommandId are required");
ModuleConfig? moduleConfig = _installedModules.Values
.FirstOrDefault(x => x.ModuleId == moduleId);
if (moduleConfig is null)
return BadRequest("Module not found");
string? queue = moduleConfig.LaunchSettings?.Queue;
if (string.IsNullOrEmpty(queue))
return BadRequest("Module does not have a queue");
var payload = await CreatePayload("",
new RouteQueueInfo("", "POST", queue, command));
var response = await _dispatcher.SendRequestAsync(queue, payload).ConfigureAwait(false);
if (response is null)
{
return NotFound();
}
else if (response is string responseString && !string.IsNullOrWhiteSpace(responseString))
{
JsonObject? responseObject = null;
responseObject = JsonSerializer.Deserialize<JsonObject>(responseString) ?? new JsonObject();
// Add common reporting properties
if (responseObject is not null)
{
responseObject["timestampUTC"] = DateTime.UtcNow.ToString("R");
// Or to create a form that show DateKind, use
// responseObject["timestampUTC"] = DateTime.Now.ToUniversalTime().ToString("O");
// Report to debug
// long timeMs = responseObject["analysisRoundTripMs"]?.GetValue<long>() ?? 0;
// Debug.WriteLine($"INFO: {pathSuffix} call processed in {timeMs}ms");
responseString = JsonSerializer.Serialize(responseObject);
return new ContentResult
{
Content = responseString,
ContentType = "application/json",
StatusCode = StatusCodes.Status200OK
};
}
}
return new ObjectResult(response);
}
/// <summary>
/// Gets a summary, in Markdown form, of the API for each module.
/// </summary>
[HttpGet("api")]
public IActionResult ApiSummary()
{
CodeExampleGenerator sampleGenerator = new CodeExampleGenerator();
TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;
StringBuilder summary = new StringBuilder();
IOrderedEnumerable<ModuleConfig> moduleList = _installedModules.Values
.Where(module => module.RouteMaps?.Length > 0
&& (module.InstallOptions?.ModuleLocation == SDK.Modules.ModuleLocation.External ||
module.InstallOptions?.ModuleLocation == SDK.Modules.ModuleLocation.Internal))
.OrderBy(module => module.PublishingInfo!.Category)
.ThenBy(module => module.Name)
.ThenBy(module => module.RouteMaps[0].Route);
string currentCategory = string.Empty;
foreach (ModuleConfig module in moduleList)
{
string category = module.PublishingInfo!.Category ?? "Uncategorised";
if (category != currentCategory)
{
if (currentCategory == string.Empty)
summary.Append("\n\n\n");
summary.Append($"## {textInfo.ToTitleCase(category)}\n\n");
currentCategory = category;
}
foreach (ModuleRouteInfo routeInfo in module.RouteMaps)
{
string url = "http://localhost:32168";
int index = routeInfo.Route.IndexOf('/');
string version = "v1";
string route = index > 0 ? routeInfo.Route.Substring(index + 1) : string.Empty;
string path = $"{version}/{routeInfo.Route}";
summary.Append($"### {routeInfo.Name}\n\n");
summary.Append($"{routeInfo.Description}\n\n");
summary.Append($"``` title=''\n");
summary.Append($"{routeInfo.Method}: {url}/{path}\n");
summary.Append($"```\n\n");
if (module.InstallOptions?.Platforms is not null)
{
summary.Append($"**Platforms**\n\n");
for (int i = 0; i < module.InstallOptions.Platforms.Length; i++)
{
string platform = module.InstallOptions.Platforms[i].ToLower() == "macos"
? "macOS" : textInfo.ToTitleCase(module.InstallOptions.Platforms[i]);
summary.Append(platform);
if (i < module.InstallOptions.Platforms.Length - 1)
summary.Append(", ");
}
summary.Append("\n\n");
}
summary.Append($"**Parameters**\n\n");
if (routeInfo.Inputs is null)
{
summary.Append("(None)\n\n");
}
else
{
foreach (RouteParameterInfo input in routeInfo.Inputs)
{
summary.AppendLine($" - **{input.Name}** ({input.Type}): {input.Description}");
if (!string.IsNullOrWhiteSpace(input.DefaultValue))
summary.AppendLine($" *Optional*. Defaults to {input.DefaultValue}");
summary.AppendLine();
}
}
summary.Append($"**Response**\n\n");
if (routeInfo.ReturnedOutputs is null)
{
summary.Append("(None)\n\n");
}
else
{
summary.Append("``` json\n");
summary.Append("{\n");
foreach (RouteParameterInfo output in routeInfo.ReturnedOutputs)
summary.Append($" \"{output.Name}\": ({output.Type}) // {output.Description}\n");
summary.Append("}\n");
summary.Append("```\n");
}
string sample = sampleGenerator.GenerateJavascript(routeInfo);
if (!string.IsNullOrWhiteSpace(sample))
{
summary.Append("\n\n");
summary.Append("#### Example\n\n");
summary.Append(sample);
}
summary.Append("\n\n\n");
}
}
return new ObjectResult(summary.ToString());
}
/// <summary>
/// Passes a request to a remote server
/// </summary>
/// <param name="pathSuffix">The path for this request without the "v1". This will be in the
/// form "category/module[/command]". eg "image/alpr" or "vision/custom/modelName".</param>
/// <param name="server">The server that will be handling this request</param>
/// <returns>An IActionResult</returns>
// private async Task<IActionResult> DispatchRemoteRequest(string pathSuffix,
private async Task<object?> DispatchRemoteRequest(string pathSuffix,
MeshServerRoutingEntry server)
{
Stopwatch sw = Stopwatch.StartNew();
HttpResponseMessage? response = null;
JsonObject? responseObject = null;
string? error = string.Empty;
long elapsedMs;
try
{
response = await ForwardAsync(server).ConfigureAwait(false);
elapsedMs = sw.ElapsedMilliseconds;
if (response?.IsSuccessStatusCode ?? false)
{
responseObject = response!.Content.ReadFromJsonAsync<JsonObject>().Result;
// Sniff for success
if (!responseObject!.ContainsKey("success") || !(bool)responseObject["success"]!)
{
elapsedMs = 30_000;
}
}
else
{
if (responseObject?.ContainsKey("error") == true)
error = $"{responseObject!["error"]} ({server.Status.Hostname})";
else
error = $"Error in DispatchRemoteRequest ({server.Status.Hostname})";
elapsedMs = 30_000;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error in DispatchRemoteRequest ({Hostname})", server.Status.Hostname);
// Bump the response to 30s to push this server out of contention.
error = $"Exception when forwarding request to {server.Status.Hostname}: {ex.Message}";
elapsedMs = 30_000;
}
finally
{
response?.Dispose();
}
if (responseObject is null)
{
// TODO: Surely there's a better way to do this
var resp = new ServerErrorResponse(error, HttpStatusCode.InternalServerError);
string jsonString = JsonSerializer.Serialize(resp);
responseObject = JsonSerializer.Deserialize<JsonObject>(jsonString);
}
_meshManager.AddResponseTime(server, pathSuffix, (int)elapsedMs);
// Add more info to the response object
if (responseObject!.ContainsKey("analysisRoundTripMs"))
responseObject["analysisRoundTripMs"] = elapsedMs;
responseObject["processedBy"] = server.Status.Hostname;
return responseObject;
/*
responseObject["timestampUTC"] = DateTime.UtcNow.ToString("R");
// Or to create a form that show DateKind, use
// responseObject["timestampUTC"] = DateTime.Now.ToUniversalTime().ToString("O");
// We don't update a module's status when that module is on a remove server
// _moduleProcessService.UpdateProcessStatusData(responseObject);
// Don't use JsonResult as it will chunk the response and Blue Iris will roll over and
// die.
string responseString = JsonSerializer.Serialize(responseObject);
return new ContentResult
{
Content = responseString,
ContentType = "application/json",
// NOTE: Always return a 200 even if the remote server failed. We are returning just
// fine, and if the remote server failed then our Content will contain an object
// that has success = false and an error message. However, the HTTP call itself was
// still successful.
StatusCode = StatusCodes.Status200OK
};
*/
}
/// <summary>
/// Passes a request to the local (current) server
/// </summary>
/// <param name="pathSuffix">The path for this request without the "v1". This will be in the
/// form "category/module[/command]". eg "image/alpr" or "vision/custom/modelName".</param>
/// <param name="routeInfo">The route and queue to which this request should be placed</param>
/// <returns>An IActionResult</returns>
// private async Task<IActionResult> DispatchLocalRequest(string pathSuffix, RouteQueueInfo routeInfo)
private async Task<object?> DispatchLocalRequest(string pathSuffix, RouteQueueInfo routeInfo)
{
// TODO: We have enough info in the routeInfo object to be able to validate that the
// request by checking that all the required values are present. Let's do that.
RequestPayload payload = await CreatePayload(pathSuffix, routeInfo!);
Stopwatch sw = Stopwatch.StartNew();
object response = await _dispatcher.SendRequestAsync(routeInfo!.QueueName, payload)
.ConfigureAwait(false);
long analysisRoundTripMs = sw.ElapsedMilliseconds;
// if the response is a string, it was returned from the backend analysis module.
if (response is string responseString)
{
// Unwrap the response and add the analysisRoundTripMs property
JsonObject? responseObject = null;
if (!string.IsNullOrEmpty(responseString))
responseObject = JsonSerializer.Deserialize<JsonObject>(responseString);
responseObject ??= new JsonObject();
responseObject["analysisRoundTripMs"] = analysisRoundTripMs;
responseObject["processedBy"] = "localhost";
// responseObject["timestampUTC"] = DateTime.UtcNow.ToString("R");
// Or to create a form that show DateKind, use
// responseObject["timestampUTC"] = DateTime.Now.ToUniversalTime().ToString("O");
_meshManager.AddResponseTime(null, pathSuffix, (int)analysisRoundTripMs);
string? moduleId = responseObject?["moduleId"]?.GetValue<string>();
if (!string.IsNullOrWhiteSpace(moduleId))
{
_moduleProcessService.UpdateModuleLastSeen(moduleId);
var statusData = responseObject?["statusData"] as JsonObject;
if (statusData is not null)
_moduleProcessService.UpdateProcessStatusData(moduleId, statusData);
}
return responseObject;
/*
// Check for, and execute if needed, triggers
ProcessTriggers(routeInfo!.QueueName, responseObject);
// Wrap it back up. Don't use JsonResult as it will chunk the response and Blue Iris
// will roll over and die.
responseString = JsonSerializer.Serialize(responseObject) as string;
return new ContentResult
{
Content = responseString,
ContentType = "application/json",
StatusCode = StatusCodes.Status200OK
};
*/
}
else
{
return response;
// return new ObjectResult(response);
}
}
/// <summary>
/// Forwards the request to the target server.
/// </summary>
/// <param name="server">The MeshServerStatus of the target server.</param>
/// <returns>A HttpResponseMessage</returns>
private async Task<HttpResponseMessage> ForwardAsync(MeshServerRoutingEntry server)
{
HttpRequest originalRequest = Request;
// The body may already have been read once by ASP.NET Core's own model-binding
// pipeline before this point. EnableBuffering() (see Startup.cs) makes the body
// seekable so we can safely rewind it here and forward the full original content.
if (originalRequest.Body.CanSeek)
originalRequest.Body.Position = 0;
int? port = originalRequest.Host.Port;
string portString = port.HasValue ? $":{port}" : string.Empty;
var queryString = originalRequest.QueryString;
string hostname = server.CallableHostname;
if (!_meshManager.RouteViaHostName && server.EndPointIPAddress is not null)
hostname = server.EndPointIPAddress;
string url = $"http://{hostname}{portString}{originalRequest.Path}{queryString}";
// Create a new request with the same method, headers and content as the original request
HttpRequestMessage newRequest = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = new StreamContent(originalRequest.Body)
};
foreach (KeyValuePair<string, Microsoft.Extensions.Primitives.StringValues> header in originalRequest.Headers)
{
if (!newRequest.Headers.TryAddWithoutValidation(header.Key, header.Value.AsEnumerable()))
newRequest.Content!.Headers.TryAddWithoutValidation(header.Key, header.Value.AsEnumerable());
}
newRequest.Headers.Add(CPAI_Forwarded_Header, "true");
// Send the new request to the target server and get the response
HttpResponseMessage response = await _httpClient.SendAsync(newRequest);
return response;
}
private async Task<RequestPayload> CreatePayload(string pathSuffix, RouteQueueInfo routeInfo)
{
// TODO: Add Segment list (string[]) and params (map of name/value)
string endOfUrl = pathSuffix.Remove(0, routeInfo.Route.Length);
var segments = new List<string>();
var queryParams = new List<KeyValuePair<string, string?[]>>();
var formFiles = new List<RequestFormFile>();
if (endOfUrl.StartsWith("/"))
endOfUrl = endOfUrl[1..];
// handle extra segments
if (endOfUrl.Length > 0)
segments.AddRange(endOfUrl.Split('/', StringSplitOptions.TrimEntries));
// and the QueryString parameters
IQueryCollection queryParts = Request.Query;
if (queryParts?.Any() ?? false)
{
foreach (KeyValuePair<string, Microsoft.Extensions.Primitives.StringValues> param in queryParts)
queryParams.Add(new KeyValuePair<string, string?[]>(param.Key, param.Value.ToArray()));
}
// We first check if the request is in JSON form. The HasFormContentType check should be
// sufficient since it checks for multipart/form-data and application/x-www-form-urlencoded.
// There should be no need to use a try/catch here either, but the GetFileData() method
// might throw if the moon is in the wrong phase.
if (Request.HasJsonContentType() && Request.ContentLength > 0)
{
var payload = await Request.ReadFromJsonAsync<RequestPayload>() ?? new RequestPayload();
payload.urlSegments = segments.ToArray();
payload.command = routeInfo.Command;
return payload;
}
else if (Request.HasFormContentType && Request.Form is not null)
{
try // if there are no Form values, then Request.Form throws.
{
IFormCollection form = Request.Form;
// Add any Form values.
queryParams.AddRange(form.Select(x =>
new KeyValuePair<string, string?[]>(x.Key, x.Value.ToArray())));
// Add any form files
formFiles.AddRange(form.Files.Select(x => new RequestFormFile
{
name = x.Name,
filename = x.FileName,
contentType = x.ContentType,
data = GetFileData(x)
}));
}
catch
{
// nothing to do here, just no Form available
}
RequestPayload payload = new RequestPayload
{
urlSegments = segments.ToArray(),
command = routeInfo.Command,
values = queryParams,
files = formFiles
};
return payload;
}
return new RequestPayload
{
urlSegments = segments.ToArray(),
command = routeInfo.Command,
};
}
private byte[] GetFileData(IFormFile x)
{
using Stream stream = x.OpenReadStream();
using BinaryReader reader = new BinaryReader(stream, Encoding.UTF8, false);
byte[] data = new byte[x.Length];
reader.Read(data, 0, data.Length);
return data;
}
// TODO: This needs to be done in the background or else this will slow down the responses
private void ProcessTriggers(string queueName, JsonObject response)
{
if (_triggersConfig.Triggers is null || _triggersConfig.Triggers.Length == 0)
return;
string platform = SystemInfo.Platform;
try
{
foreach (Trigger trigger in _triggersConfig.Triggers)
{
// If the trigger is queue specific, check
if (!string.IsNullOrWhiteSpace(trigger.Queue) &&
!trigger.Queue.EqualsIgnoreCase(queueName))
continue;
// Is there a task to run on this platform, and a property to look for?
TriggerTask? task = trigger.GetTask(platform);
if (string.IsNullOrEmpty(trigger.PropertyName) || task is null ||
string.IsNullOrEmpty(task.Command))
continue;
if (string.IsNullOrWhiteSpace(trigger.PredictionsCollectionName))
{
float.TryParse(response["confidence"]?.ToString(), out float confidence);
string? value = response[trigger.PropertyName]?.ToString();
if (trigger.Test(value, confidence))
_commandRunner.RunCommand(task);
}
else
{
JsonNode? predictions = response[trigger.PredictionsCollectionName];
if (predictions is not null)
{
foreach (JsonNode? prediction in predictions.AsArray())
{
if (prediction is null)
continue;
float.TryParse(prediction["confidence"]?.ToString(), out float confidence);
string? value = prediction[trigger.PropertyName]?.ToString();
if (trigger.Test(value, confidence))
_commandRunner.RunCommand(task);
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error processing triggers: " + ex.Message);
}
}
}
}