-
Notifications
You must be signed in to change notification settings - Fork 266
/
DurableHttpRequest.cs
272 lines (240 loc) · 11.4 KB
/
DurableHttpRequest.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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Net.Http;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.WebJobs.Extensions.DurableTask
{
/// <summary>
/// Request used to make an HTTP call through Durable Functions.
/// </summary>
public class DurableHttpRequest
{
/// <summary>
/// Initializes a new instance of the <see cref="DurableHttpRequest"/> class.
/// </summary>
/// <param name="method">Method used for HTTP request.</param>
/// <param name="uri">Uri used to make the HTTP request.</param>
/// <param name="headers">Headers added to the HTTP request.</param>
/// <param name="content">Content added to the body of the HTTP request.</param>
/// <param name="tokenSource">AAD authentication attached to the HTTP request.</param>
/// <param name="asynchronousPatternEnabled">Specifies whether the DurableHttpRequest should handle the asynchronous pattern.</param>
/// <param name="timeout">TimeSpan used for HTTP request timeout.</param>
/// <param name="httpRetryOptions">Retry options used for the HTTP request.</param>
public DurableHttpRequest(
HttpMethod method,
Uri uri,
IDictionary<string, StringValues> headers = null,
string content = null,
ITokenSource tokenSource = null,
bool asynchronousPatternEnabled = true,
TimeSpan? timeout = null,
HttpRetryOptions httpRetryOptions = null)
{
this.Method = method;
this.Uri = uri;
this.Headers = HttpHeadersConverter.CreateCopy(headers);
this.Content = content;
this.TokenSource = tokenSource;
this.AsynchronousPatternEnabled = asynchronousPatternEnabled;
this.Timeout = timeout;
this.HttpRetryOptions = httpRetryOptions;
}
/// <summary>
/// HttpMethod used in the HTTP request made by the Durable Function.
/// </summary>
[JsonProperty("method")]
[JsonConverter(typeof(HttpMethodConverter))]
public HttpMethod Method { get; }
/// <summary>
/// Uri used in the HTTP request made by the Durable Function.
/// </summary>
[JsonProperty("uri")]
public Uri Uri { get; }
/// <summary>
/// Headers passed with the HTTP request made by the Durable Function.
/// </summary>
[JsonProperty("headers")]
[JsonConverter(typeof(HttpHeadersConverter))]
public IDictionary<string, StringValues> Headers { get; }
/// <summary>
/// Content passed with the HTTP request made by the Durable Function.
/// </summary>
[JsonProperty("content")]
public string Content { get; }
/// <summary>
/// Mechanism for attaching an OAuth token to the request.
/// </summary>
[JsonProperty("tokenSource")]
[JsonConverter(typeof(TokenSourceConverter))]
public ITokenSource TokenSource { get; }
/// <summary>
/// Specifies whether the Durable HTTP APIs should automatically
/// handle the asynchronous HTTP pattern.
/// </summary>
[JsonProperty("asynchronousPatternEnabled")]
public bool AsynchronousPatternEnabled { get; }
/// <summary>
/// Defines retry policy for handling of failures in making the HTTP Request. These could be non-successful HTTP status codes
/// in the response, a timeout in making the HTTP call, or an exception raised from the HTTP Client library.
/// </summary>
[JsonProperty("retryOptions")]
public HttpRetryOptions HttpRetryOptions { get; }
/// <summary>
/// The total timeout for the original HTTP request and any
/// asynchronous polling.
/// </summary>
[JsonProperty("timeout")]
public TimeSpan? Timeout { get; }
private class HttpMethodConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(HttpMethod);
}
public override object ReadJson(
JsonReader reader,
Type objectType,
object existingValue,
JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.String)
{
return new HttpMethod((string)JToken.Load(reader));
}
// Default for JSON that's either missing or not understood
return HttpMethod.Get;
}
public override void WriteJson(
JsonWriter writer,
object value,
JsonSerializer serializer)
{
HttpMethod method = (HttpMethod)value ?? HttpMethod.Get;
writer.WriteValue(method.ToString());
}
}
private class TokenSourceConverter : JsonConverter
{
private static JsonSerializer tokenSerializer;
private enum TokenSourceType
{
None = 0,
AzureManagedIdentity = 1,
}
public override bool CanConvert(Type objectType)
{
return objectType is ITokenSource;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var safeTokenSerializer = GetTokenSourceSerializer(serializer);
JToken json = JToken.ReadFrom(reader);
if (json.Type == JTokenType.Null)
{
return null;
}
JObject jsonObject = (JObject)json;
if (jsonObject.TryGetValue("kind", out JToken kindValue))
{
if (Enum.TryParse((string)kindValue, out TokenSourceType tokenSourceKind) &&
tokenSourceKind == TokenSourceType.AzureManagedIdentity)
{
string resourceString = (string)jsonObject.GetValue("resource", StringComparison.Ordinal);
if (jsonObject.TryGetValue("options", out JToken optionsToken))
{
ManagedIdentityOptions managedIdentityOptions = optionsToken.ToObject<JObject>().ToObject<ManagedIdentityOptions>();
return new ManagedIdentityTokenSource(resourceString, managedIdentityOptions);
}
return new ManagedIdentityTokenSource(resourceString);
}
throw new NotSupportedException($"The token source kind '{kindValue.ToString(Formatting.None)}' is not supported.");
}
else if (jsonObject.TryGetValue("$type", StringComparison.Ordinal, out JToken clrTypeValue))
{
Type runtimeType = Type.GetType((string)clrTypeValue, throwOnError: true);
return jsonObject.ToObject(runtimeType, safeTokenSerializer);
}
else
{
// Don't know how to deserialize this - use default behavior (this may fail)
return jsonObject.ToObject(objectType);
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is ManagedIdentityTokenSource tokenSource)
{
writer.WriteStartObject();
writer.WritePropertyName("kind");
writer.WriteValue(TokenSourceType.AzureManagedIdentity.ToString());
writer.WritePropertyName("resource");
writer.WriteValue(tokenSource.Resource);
if (tokenSource.Options != null)
{
writer.WritePropertyName("options");
writer.WriteRawValue(JsonConvert.SerializeObject(tokenSource.Options));
}
writer.WriteEndObject();
}
else
{
// Don't know how to serialize this - use default behavior, forcing TypeNameHandling.Objects to correctly serialize ITokenSource
var safeTokenSerializer = GetTokenSourceSerializer(serializer);
safeTokenSerializer.Serialize(writer, value);
}
}
private static JsonSerializer GetTokenSourceSerializer(JsonSerializer serializer)
{
if (tokenSerializer != null)
{
return tokenSerializer;
}
if (serializer.TypeNameHandling == TypeNameHandling.Objects
|| serializer.TypeNameHandling == TypeNameHandling.All)
{
tokenSerializer = serializer;
return tokenSerializer;
}
// Make sure these are all the settings when updating Newtonsoft.Json
tokenSerializer = new JsonSerializer
{
Context = serializer.Context,
Culture = serializer.Culture,
ContractResolver = serializer.ContractResolver,
ConstructorHandling = serializer.ConstructorHandling,
CheckAdditionalContent = serializer.CheckAdditionalContent,
DateFormatHandling = serializer.DateFormatHandling,
DateFormatString = serializer.DateFormatString,
DateParseHandling = serializer.DateParseHandling,
DateTimeZoneHandling = serializer.DateTimeZoneHandling,
DefaultValueHandling = serializer.DefaultValueHandling,
EqualityComparer = serializer.EqualityComparer,
FloatFormatHandling = serializer.FloatFormatHandling,
Formatting = serializer.Formatting,
FloatParseHandling = serializer.FloatParseHandling,
MaxDepth = serializer.MaxDepth,
MetadataPropertyHandling = serializer.MetadataPropertyHandling,
MissingMemberHandling = serializer.MissingMemberHandling,
NullValueHandling = serializer.NullValueHandling,
ObjectCreationHandling = serializer.ObjectCreationHandling,
PreserveReferencesHandling = serializer.PreserveReferencesHandling,
ReferenceResolver = serializer.ReferenceResolver,
ReferenceLoopHandling = serializer.ReferenceLoopHandling,
StringEscapeHandling = serializer.StringEscapeHandling,
TraceWriter = serializer.TraceWriter,
// Enforcing TypeNameHandling.Objects to make sure ITokenSource gets serialized/deserialized correctly
TypeNameHandling = TypeNameHandling.Objects,
};
foreach (var converter in serializer.Converters)
{
tokenSerializer.Converters.Add(converter);
}
return tokenSerializer;
}
}
}
}