-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
SignalRInvocationMethodExecutor.cs
80 lines (71 loc) · 3.2 KB
/
SignalRInvocationMethodExecutor.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR.Protocol;
using InvocationMessage = Microsoft.Azure.SignalR.Serverless.Protocols.InvocationMessage;
namespace Microsoft.Azure.WebJobs.Extensions.SignalRService
{
internal class SignalRInvocationMethodExecutor : SignalRMethodExecutor
{
public SignalRInvocationMethodExecutor(IRequestResolver resolver, ExecutionContext executionContext) : base(resolver, executionContext)
{
}
public override async Task<HttpResponseMessage> ExecuteAsync(HttpRequestMessage request)
{
if (!Resolver.TryGetInvocationContext(request, out var context))
{
//TODO: More detailed exception
throw new SignalRTriggerException();
}
var (message, protocol) = await Resolver.GetMessageAsync<InvocationMessage>(request).ConfigureAwait(false);
AssertConsistency(context, message);
context.Arguments = message.Arguments;
// Only when it's an invoke, we need the result from function execution.
TaskCompletionSource<object> tcs = null;
if (!string.IsNullOrEmpty(message.InvocationId))
{
tcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
}
HttpResponseMessage response;
CompletionMessage completionMessage = null;
var functionResult = await ExecuteWithAuthAsync(request, ExecutionContext, context, tcs).ConfigureAwait(false);
if (tcs != null)
{
if (!functionResult.Succeeded)
{
var errorMessage = functionResult.Exception?.InnerException?.Message ??
functionResult.Exception?.Message ??
"Method execution failed.";
completionMessage = CompletionMessage.WithError(message.InvocationId, errorMessage);
response = new HttpResponseMessage(HttpStatusCode.OK);
}
else
{
var result = await tcs.Task.ConfigureAwait(false);
completionMessage = CompletionMessage.WithResult(message.InvocationId, result);
response = new HttpResponseMessage(HttpStatusCode.OK);
}
}
else
{
response = new HttpResponseMessage(HttpStatusCode.OK);
}
if (completionMessage != null)
{
response.Content = new ByteArrayContent(protocol.GetMessageBytes(completionMessage).ToArray());
}
return response;
}
private static void AssertConsistency(InvocationContext context, InvocationMessage message)
{
if (!string.Equals(context.Event, message.Target, StringComparison.OrdinalIgnoreCase))
{
// TODO: More detailed exception
throw new SignalRTriggerException();
}
}
}
}