-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathConnection.cs
251 lines (227 loc) · 12.6 KB
/
Connection.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
/*
* Copyright 2017 Stanislav Muhametsin. All rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using CBAM.Abstractions;
using CBAM.HTTP;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using UtilPack;
namespace CBAM.HTTP
{
/// <summary>
/// This interface extends <see cref="Connection{TStatement, TStatementInformation, TStatementCreationArgs, TEnumerableItem, TVendorFunctionality}"/> to provide a way to create statements which enable sending <see cref="HTTPRequest"/>s to server.
/// </summary>
/// <typeparam name="TRequestMetaData">The type of metadata associated with each request, used in identifying the request that response is associated with. Typically this is <see cref="Guid"/> or <see cref="Int64"/>.</typeparam>
public interface HTTPConnection<TRequestMetaData> : Connection<HTTPStatement<TRequestMetaData>, HTTPStatementInformation<TRequestMetaData>, HTTPRequestInfo<TRequestMetaData>, HTTPResponseInfo<TRequestMetaData>, HTTPConnectionVendorFunctionality<TRequestMetaData>>
{
/// <summary>
/// Gets the HTTP protocol version used by this <see cref="HTTPConnection{TRequestMetaData}"/>.
/// </summary>
String ProtocolVersion { get; }
}
/// <summary>
/// This interface extends <see cref="ConnectionVendorFunctionality{TStatement, TStatementCreationArgs}"/> to provide any HTTP-specific functionality which does not need a connection.
/// Currently, there are none, but there might be some in the future.
/// </summary>
/// <typeparam name="TRequestMetaData">The type of metadata associated with each request, used in identifying the request that response is associated with. Typically this is <see cref="Guid"/> or <see cref="Int64"/>.</typeparam>
public interface HTTPConnectionVendorFunctionality<TRequestMetaData> : ConnectionVendorFunctionality<HTTPStatement<TRequestMetaData>, HTTPRequestInfo<TRequestMetaData>>
{
}
/// <summary>
/// This is information associated with a single response.
/// </summary>
/// <typeparam name="TRequestMetaData">The type of the metadata of the request that this response is associated with. Typically this is <see cref="Guid"/> or <see cref="Int64"/>.</typeparam>
public struct HTTPResponseInfo<TRequestMetaData>
{
/// <summary>
/// Creates a new instance of <see cref="HTTPResponseInfo{TRequestMetaData}"/> with given parameters.
/// </summary>
/// <param name="response">The <see cref="HTTPResponse"/>.</param>
/// <param name="metadata">The metadata of the request that <paramref name="response"/> is associated with.</param>
/// <exception cref="ArgumentNullException">If <paramref name="response"/> is <c>null</c>.</exception>
public HTTPResponseInfo(
HTTPResponse response,
TRequestMetaData metadata
)
{
this.Response = ArgumentValidator.ValidateNotNull( nameof( response ), response );
this.RequestMetaData = metadata;
}
/// <summary>
/// Gets the <see cref="HTTPResponse"/> of this <see cref="HTTPResponseInfo{TRequestMetaData}"/>.
/// </summary>
/// <value>The <see cref="HTTPResponse"/> of this <see cref="HTTPResponseInfo{TRequestMetaData}"/>.</value>
public HTTPResponse Response { get; }
/// <summary>
/// Gets the metadata of the request that <see cref="Response"/> is associated with.
/// </summary>
/// <value>The metadata of the request that <see cref="Response"/> is associated with.</value>
public TRequestMetaData RequestMetaData { get; }
}
/// <summary>
/// This struct binds together the <see cref="HTTPRequest"/> and metadata.
/// </summary>
/// <typeparam name="TRequestMetaData">The type of metadata of the request. Typically this is <see cref="Guid"/> or <see cref="Int64"/>.</typeparam>
public struct HTTPRequestInfo<TRequestMetaData>
{
/// <summary>
/// Creates a new instance of <see cref="HTTPRequestInfo{TRequestMetaData}"/> with given parameters.
/// </summary>
/// <param name="request">The <see cref="HTTPRequest"/>. May be <c>null</c>.</param>
/// <param name="metadata">The metadata of the <paramref name="request"/>.</param>
public HTTPRequestInfo(
HTTPRequest request,
TRequestMetaData metadata
)
{
this.Request = request;
this.RequestMetaData = metadata;
}
/// <summary>
/// Gets the <see cref="HTTPRequest"/> of this <see cref="HTTPRequestInfo{TRequestMetaData}"/>.
/// </summary>
/// <value></value>
public HTTPRequest Request { get; }
/// <summary>
/// Gets the metadata of the <see cref="Request"/>.
/// </summary>
/// <value>The metadata of the <see cref="Request"/>.</value>
public TRequestMetaData RequestMetaData { get; }
}
/// <summary>
/// This class is meant to be used in simple situations, when the textual content of the HTTP response is meant to be created, without handling memory and performance or stream copying manually.
/// </summary>
/// <seealso cref="E_CBAM.CreateTextualResponseInfoAsync"/>
public sealed class HTTPTextualResponseInfo
{
private static readonly Encoding DefaultTextEncoding = new UTF8Encoding( false, false );
/// <summary>
/// Creates a new instance of <see cref="HTTPTextualResponseInfo"/> with given parameters.
/// </summary>
/// <param name="response">The <see cref="HTTPResponse"/>.</param>
/// <param name="content">The content of the <see cref="HTTPResponse"/>, as byte array.</param>
/// <param name="defaultEncoding">The default <see cref="Encoding"/> to use if no encoding can be deduced from <see cref="HTTPResponse"/>. If <c>null</c>, then <see cref="UTF8Encoding"/> will be used.</param>
/// <exception cref="ArgumentNullException">If <paramref name="response"/> is <c>null</c>.</exception>
public HTTPTextualResponseInfo(
HTTPResponse response,
Byte[] content,
Encoding defaultEncoding
)
{
ArgumentValidator.ValidateNotNull( nameof( response ), response );
this.Version = response.Version;
this.StatusCode = response.StatusCode;
this.Message = response.StatusCodeMessage;
this.Headers = response.Headers;
String textualContent;
if ( !content.IsNullOrEmpty() )
{
String cType;
Int32 charsetIndex;
Int32 charsetEndIdx;
var encoding = response.Headers.TryGetValue( "Content-Type", out var cTypes ) && cTypes.Count > 0 && ( charsetIndex = ( cType = cTypes[0] ).IndexOf( "charset=" ) ) >= 0 ?
Encoding.GetEncoding( cType.Substring( charsetIndex + 8, ( ( charsetEndIdx = cType.IndexOf( ';', charsetIndex + 9 ) ) > 0 ? charsetEndIdx : cType.Length ) - charsetIndex - 8 ) ) :
( defaultEncoding ?? DefaultTextEncoding );
textualContent = encoding.GetString( content, 0, content.Length );
}
else
{
textualContent = String.Empty;
}
this.TextualContent = textualContent;
}
/// <summary>
/// Gets the <see cref="HTTPMessage{TContent, TDictionary, TList}.Version"/> of the <see cref="HTTPResponse"/> this <see cref="HTTPTextualResponseInfo"/> was created from.
/// </summary>
/// <value>The <see cref="HTTPMessage{TContent, TDictionary, TList}.Version"/> of the <see cref="HTTPResponse"/> this <see cref="HTTPTextualResponseInfo"/> was created from.</value>
public String Version { get; }
/// <summary>
/// Gets the <see cref="HTTPResponse.StatusCode"/> of the <see cref="HTTPResponse"/> this <see cref="HTTPTextualResponseInfo"/> was created from.
/// </summary>
/// <value>The <see cref="HTTPResponse.StatusCode"/> of the <see cref="HTTPResponse"/> this <see cref="HTTPTextualResponseInfo"/> was created from.</value>
public Int32 StatusCode { get; }
/// <summary>
/// Gets the <see cref="HTTPResponse.StatusCodeMessage"/> of the <see cref="HTTPResponse"/> this <see cref="HTTPTextualResponseInfo"/> was created from.
/// </summary>
/// <value>The <see cref="HTTPResponse.StatusCodeMessage"/> of the <see cref="HTTPResponse"/> this <see cref="HTTPTextualResponseInfo"/> was created from.</value>
public String Message { get; }
/// <summary>
/// Gets the <see cref="HTTPMessage{TContent, TDictionary, TList}.Headers"/> of the <see cref="HTTPResponse"/> this <see cref="HTTPTextualResponseInfo"/> was created from.
/// </summary>
/// <value>the <see cref="HTTPMessage{TContent, TDictionary, TList}.Headers"/> of the <see cref="HTTPResponse"/> this <see cref="HTTPTextualResponseInfo"/> was created from.</value>
public IReadOnlyDictionary<String, IReadOnlyList<String>> Headers { get; }
/// <summary>
/// Gets the deserialized <see cref="HTTPResponseContent"/> as <see cref="String"/>.
/// </summary>
/// <value>The deserialized <see cref="HTTPResponseContent"/> as <see cref="String"/>.</value>
public String TextualContent { get; }
}
}
/// <summary>
/// This class contains extension methods for types defined in this assembly.
/// </summary>
public static partial class E_CBAM
{
/// <summary>
/// This method will asynchronously receive one <see cref="HTTPTextualResponseInfo"/> from this <see cref="HTTPConnection{TRequestMetaData}"/>, after sending a given <see cref="HTTPRequest"/>.
/// </summary>
/// <typeparam name="TRequestMetaData">The type of metadata associated with given <see cref="HTTPRequest"/>. Typically this is <see cref="Guid"/> or <see cref="Int64"/>.</typeparam>
/// <param name="connection">This <see cref="HTTPConnection{TRequestMetaData}"/>.</param>
/// <param name="request">The <see cref="HTTPRequest"/> to send.</param>
/// <param name="metaData">The metadata of the <paramref name="request"/>.</param>
/// <param name="defaultEncoding">The default encoding to use when deserializing response contents to string. By default, it is <see cref="UTF8Encoding"/>.</param>
/// <returns>Potentially asynchronously creates constructed <see cref="HTTPTextualResponseInfo"/>.</returns>
/// <exception cref="NullReferenceException">If this <see cref="HTTPConnection{TRequestMetaData}"/> is <c>null</c>.</exception>
public static Task<HTTPTextualResponseInfo> ReceiveOneTextualResponseAsync<TRequestMetaData>(
this HTTPConnection<TRequestMetaData> connection,
HTTPRequest request,
TRequestMetaData metaData = default,
Encoding defaultEncoding = default
)
{
return connection
.PrepareStatementForExecution( new HTTPRequestInfo<TRequestMetaData>( request, metaData ) )
.Select( async responseInfo => await responseInfo.Response.CreateTextualResponseInfoAsync( defaultEncoding ) )
.FirstAsync();
}
/// <summary>
/// Asynchronously creates <see cref="HTTPTextualResponseInfo"/> from this <see cref="HTTPResponse"/>.
/// </summary>
/// <param name="response">This <see cref="HTTPResponse"/>.</param>
/// <param name="defaultEncoding">The <see cref="Encoding"/> to use if <see cref="HTTPResponse"/> does not contain any encoding information. By default, it is <see cref="UTF8Encoding"/>.</param>
/// <returns>Potentially asynchronously creates constructed <see cref="HTTPTextualResponseInfo"/>.</returns>
/// <exception cref="NullReferenceException">If this <see cref="HTTPResponse"/> is <c>null</c>.</exception>
public static async ValueTask<HTTPTextualResponseInfo> CreateTextualResponseInfoAsync(
this HTTPResponse response,
Encoding defaultEncoding = default
)
{
var content = response.Content;
Byte[] bytes;
if ( content != null )
{
bytes = await content.ReadAllContentAsync();
}
else
{
bytes = null;
}
return new HTTPTextualResponseInfo( response, bytes, defaultEncoding );
}
}