root / trunk / Pithos.Network / PithosClient.cs @ 7d915c34
History | View | Annotate | Download (13.9 kB)
1 |
// ----------------------------------------------------------------------- |
---|---|
2 |
// <copyright file="PithosClient.cs" company="Microsoft"> |
3 |
// TODO: Update copyright text. |
4 |
// </copyright> |
5 |
// ----------------------------------------------------------------------- |
6 |
|
7 |
using System.Collections.Specialized; |
8 |
using System.Diagnostics; |
9 |
using System.Diagnostics.Contracts; |
10 |
using System.IO; |
11 |
using System.Net; |
12 |
using System.Runtime.Serialization; |
13 |
using System.Threading.Tasks; |
14 |
|
15 |
namespace Pithos.Network |
16 |
{ |
17 |
using System; |
18 |
using System.Collections.Generic; |
19 |
using System.Linq; |
20 |
using System.Text; |
21 |
|
22 |
/// <summary> |
23 |
/// TODO: Update summary. |
24 |
/// </summary> |
25 |
public class PithosClient:WebClient |
26 |
{ |
27 |
public int Timeout { get; set; } |
28 |
|
29 |
public bool TimedOut { get; set; } |
30 |
|
31 |
public HttpStatusCode StatusCode { get; private set; } |
32 |
|
33 |
public string StatusDescription { get; set; } |
34 |
|
35 |
|
36 |
public int Retries { get; set; } |
37 |
|
38 |
private readonly Dictionary<string, string> _parameters=new Dictionary<string, string>(); |
39 |
public Dictionary<string, string> Parameters |
40 |
{ |
41 |
get { return _parameters; } |
42 |
} |
43 |
|
44 |
public PithosClient():base() |
45 |
{ |
46 |
|
47 |
} |
48 |
|
49 |
|
50 |
public PithosClient(PithosClient other) |
51 |
: base() |
52 |
{ |
53 |
CopyHeaders(other); |
54 |
Timeout = other.Timeout; |
55 |
Retries = other.Retries; |
56 |
BaseAddress = other.BaseAddress; |
57 |
|
58 |
|
59 |
foreach (var parameter in other.Parameters) |
60 |
{ |
61 |
Parameters.Add(parameter.Key,parameter.Value); |
62 |
} |
63 |
|
64 |
this.Proxy = other.Proxy; |
65 |
} |
66 |
|
67 |
protected override WebRequest GetWebRequest(Uri address) |
68 |
{ |
69 |
TimedOut = false; |
70 |
HttpWebRequest request = base.GetWebRequest(address) as HttpWebRequest; |
71 |
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; |
72 |
if(Timeout>0) |
73 |
request.Timeout = Timeout; |
74 |
return request; |
75 |
} |
76 |
|
77 |
protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result) |
78 |
{ |
79 |
var response = (HttpWebResponse) base.GetWebResponse(request, result); |
80 |
StatusCode=response.StatusCode; |
81 |
StatusDescription=response.StatusDescription; |
82 |
return response; |
83 |
} |
84 |
|
85 |
|
86 |
|
87 |
protected override WebResponse GetWebResponse(WebRequest request) |
88 |
{ |
89 |
try |
90 |
{ |
91 |
|
92 |
var response = (HttpWebResponse)base.GetWebResponse(request); |
93 |
StatusCode = response.StatusCode; |
94 |
StatusDescription = response.StatusDescription; |
95 |
return response; |
96 |
} |
97 |
catch (WebException exc) |
98 |
{ |
99 |
if (exc.Response.ContentLength > 0) |
100 |
{ |
101 |
string content; |
102 |
content = GetContent(exc.Response); |
103 |
Trace.TraceError(content); |
104 |
} |
105 |
throw; |
106 |
} |
107 |
} |
108 |
|
109 |
private static string GetContent(WebResponse webResponse) |
110 |
{ |
111 |
string content; |
112 |
using (var stream = webResponse.GetResponseStream()) |
113 |
using (var reader = new StreamReader(stream)) |
114 |
{ |
115 |
content = reader.ReadToEnd(); |
116 |
} |
117 |
return content; |
118 |
} |
119 |
|
120 |
public string DownloadStringWithRetry(string address,int retries=0) |
121 |
{ |
122 |
if (address == null) |
123 |
throw new ArgumentNullException("address"); |
124 |
|
125 |
var actualAddress = GetActualAddress(address); |
126 |
|
127 |
var actualRetries = (retries == 0) ? Retries : retries; |
128 |
|
129 |
|
130 |
|
131 |
var task = Retry(() => |
132 |
{ |
133 |
var uriString = String.Join("/", BaseAddress, actualAddress); |
134 |
var content = base.DownloadString(uriString); |
135 |
|
136 |
if (StatusCode == HttpStatusCode.NoContent) |
137 |
return String.Empty; |
138 |
return content; |
139 |
|
140 |
}, actualRetries); |
141 |
|
142 |
var result = task.Result; |
143 |
return result; |
144 |
} |
145 |
|
146 |
public void Head(string address,int retries=0) |
147 |
{ |
148 |
RetryWithoutContent(address, retries, "HEAD"); |
149 |
} |
150 |
|
151 |
public void PutWithRetry(string address, int retries = 0) |
152 |
{ |
153 |
RetryWithoutContent(address, retries, "PUT"); |
154 |
} |
155 |
|
156 |
public void DeleteWithRetry(string address,int retries=0) |
157 |
{ |
158 |
RetryWithoutContent(address, retries, "DELETE"); |
159 |
} |
160 |
|
161 |
public string GetHeaderValue(string headerName) |
162 |
{ |
163 |
var values=this.ResponseHeaders.GetValues(headerName); |
164 |
if (values == null) |
165 |
throw new WebException(String.Format("The {0} header is missing", headerName)); |
166 |
else |
167 |
return values[0]; |
168 |
} |
169 |
|
170 |
private void RetryWithoutContent(string address, int retries, string method) |
171 |
{ |
172 |
if (address == null) |
173 |
throw new ArgumentNullException("address"); |
174 |
|
175 |
var actualAddress = GetActualAddress(address); |
176 |
|
177 |
var actualRetries = (retries == 0) ? Retries : retries; |
178 |
var task = Retry(() => |
179 |
{ |
180 |
var uriString = String.Join("/",BaseAddress ,actualAddress); |
181 |
var uri = new Uri(uriString); |
182 |
var request = GetWebRequest(uri); |
183 |
request.Method = method; |
184 |
if (ResponseHeaders!=null) |
185 |
ResponseHeaders.Clear(); |
186 |
|
187 |
var response = (HttpWebResponse)GetWebResponse(request); |
188 |
StatusCode = response.StatusCode; |
189 |
StatusDescription = response.StatusDescription; |
190 |
|
191 |
|
192 |
return 0; |
193 |
}, actualRetries); |
194 |
|
195 |
task.Wait(); |
196 |
} |
197 |
|
198 |
private string GetActualAddress(string address) |
199 |
{ |
200 |
if (Parameters.Count == 0) |
201 |
return address; |
202 |
var addressBuilder=new StringBuilder(address); |
203 |
|
204 |
bool isFirst = true; |
205 |
foreach (var parameter in Parameters) |
206 |
{ |
207 |
if(isFirst) |
208 |
addressBuilder.AppendFormat("?{0}={1}", parameter.Key, parameter.Value); |
209 |
else |
210 |
addressBuilder.AppendFormat("&{0}={1}", parameter.Key, parameter.Value); |
211 |
isFirst = false; |
212 |
} |
213 |
return addressBuilder.ToString(); |
214 |
} |
215 |
|
216 |
public string DownloadStringWithRetry(Uri address,int retries=0) |
217 |
{ |
218 |
if (address == null) |
219 |
throw new ArgumentNullException("address"); |
220 |
|
221 |
var actualRetries = (retries == 0) ? Retries : retries; |
222 |
var task = Retry(() => |
223 |
{ |
224 |
var content = base.DownloadString(address); |
225 |
|
226 |
if (StatusCode == HttpStatusCode.NoContent) |
227 |
return String.Empty; |
228 |
return content; |
229 |
|
230 |
}, actualRetries); |
231 |
|
232 |
var result = task.Result; |
233 |
return result; |
234 |
} |
235 |
|
236 |
|
237 |
/// <summary> |
238 |
/// Copies headers from another PithosClient |
239 |
/// </summary> |
240 |
/// <param name="source">The PithosClient from which the headers are copied</param> |
241 |
public void CopyHeaders(PithosClient source) |
242 |
{ |
243 |
Contract.Requires(source != null, "source can't be null"); |
244 |
if (source == null) |
245 |
throw new ArgumentNullException("source", "source can't be null"); |
246 |
CopyHeaders(source.Headers,Headers); |
247 |
} |
248 |
|
249 |
/// <summary> |
250 |
/// Copies headers from one header collection to another |
251 |
/// </summary> |
252 |
/// <param name="source">The source collection from which the headers are copied</param> |
253 |
/// <param name="target">The target collection to which the headers are copied</param> |
254 |
public static void CopyHeaders(WebHeaderCollection source,WebHeaderCollection target) |
255 |
{ |
256 |
Contract.Requires(source != null, "source can't be null"); |
257 |
Contract.Requires(target != null, "target can't be null"); |
258 |
if (source == null) |
259 |
throw new ArgumentNullException("source", "source can't be null"); |
260 |
if (target == null) |
261 |
throw new ArgumentNullException("target", "target can't be null"); |
262 |
for (int i = 0; i < source.Count; i++) |
263 |
{ |
264 |
target.Add(source.GetKey(i), source[i]); |
265 |
} |
266 |
} |
267 |
|
268 |
public void AssertStatusOK(string message) |
269 |
{ |
270 |
if (StatusCode >= HttpStatusCode.BadRequest) |
271 |
throw new WebException(String.Format("{0} with code {1} - {2}", message, StatusCode, StatusDescription)); |
272 |
} |
273 |
|
274 |
/*private Func<T> Retry<T>(Func< T> original, int retryCount) |
275 |
{ |
276 |
return () => |
277 |
{ |
278 |
while (true) |
279 |
{ |
280 |
try |
281 |
{ |
282 |
return original(); |
283 |
} |
284 |
catch (WebException e) |
285 |
{ |
286 |
var statusCode = ((HttpWebResponse)e.Response).StatusCode; |
287 |
this.StatusCode = statusCode; |
288 |
|
289 |
switch (e.Status) |
290 |
{ |
291 |
case WebExceptionStatus.Timeout: |
292 |
|
293 |
TimedOut = true; |
294 |
if (retryCount == 0) |
295 |
{ |
296 |
Trace.TraceError("[ERROR] Timed out too many times. {0}\n", e); |
297 |
throw new RetryException("Timed out too many times.", e); |
298 |
} |
299 |
retryCount--; |
300 |
Trace.TraceError( |
301 |
"[RETRY] Timed out after {0} ms. Will retry {1} more times\n{2}", Timeout, |
302 |
retryCount, e); |
303 |
|
304 |
break; |
305 |
case WebExceptionStatus.ProtocolError: |
306 |
switch (statusCode) |
307 |
{ |
308 |
case HttpStatusCode.NotFound: |
309 |
{ |
310 |
return default(T); |
311 |
} |
312 |
case HttpStatusCode.ServiceUnavailable: |
313 |
{ |
314 |
|
315 |
TimedOut = false; |
316 |
if (retryCount == 0) |
317 |
{ |
318 |
Trace.TraceError("[ERROR] Failed too many times. {0}\n", e); |
319 |
throw new RetryException("Failed too many times.", e); |
320 |
} |
321 |
retryCount--; |
322 |
Trace.TraceError( |
323 |
"[RETRY] Failed due to 503. Will retry {0} more times\n{1}", retryCount, e); |
324 |
break; |
325 |
} |
326 |
default: |
327 |
throw; |
328 |
} |
329 |
break; |
330 |
default: |
331 |
throw; |
332 |
} |
333 |
} |
334 |
} |
335 |
}; |
336 |
}*/ |
337 |
|
338 |
private Task<T> Retry<T>(Func< T> original, int retryCount) |
339 |
{ |
340 |
return Task.Factory.StartNew(() => original()).ContinueWith(_original => |
341 |
{ |
342 |
if(_original.IsFaulted ) |
343 |
{ |
344 |
var e = _original.Exception.InnerException; |
345 |
if (e is WebException) |
346 |
{ |
347 |
var we = (e as WebException); |
348 |
var statusCode = ((HttpWebResponse) we.Response).StatusCode; |
349 |
this.StatusCode = statusCode; |
350 |
|
351 |
if (we.Status==WebExceptionStatus.Timeout || |
352 |
(we.Status==WebExceptionStatus.ProtocolError && statusCode==HttpStatusCode.ServiceUnavailable)) |
353 |
{ |
354 |
TimedOut = true; |
355 |
if (retryCount == 0) |
356 |
{ |
357 |
Trace.TraceError("[ERROR] Timed out too many times. {0}\n", e); |
358 |
throw new RetryException("Timed out too many times.", e); |
359 |
} |
360 |
Trace.TraceError( |
361 |
"[RETRY] Timed out after {0} ms. Will retry {1} more times\n{2}", Timeout, |
362 |
retryCount, e); |
363 |
return Retry(original, retryCount - 1); |
364 |
} |
365 |
|
366 |
if (statusCode==HttpStatusCode.NotFound) |
367 |
return new Task<T>(() => default(T)); |
368 |
} |
369 |
throw e; |
370 |
} |
371 |
else |
372 |
return Task<T>.Factory.StartNew(() => _original.Result); |
373 |
}).Unwrap(); |
374 |
} |
375 |
|
376 |
|
377 |
} |
378 |
|
379 |
public class RetryException:Exception |
380 |
{ |
381 |
public RetryException() |
382 |
:base() |
383 |
{ |
384 |
|
385 |
} |
386 |
|
387 |
public RetryException(string message) |
388 |
:base(message) |
389 |
{ |
390 |
|
391 |
} |
392 |
|
393 |
public RetryException(string message,Exception innerException) |
394 |
:base(message,innerException) |
395 |
{ |
396 |
|
397 |
} |
398 |
|
399 |
public RetryException(SerializationInfo info,StreamingContext context) |
400 |
:base(info,context) |
401 |
{ |
402 |
|
403 |
} |
404 |
} |
405 |
} |