1 // -----------------------------------------------------------------------
2 // <copyright file="RestClient.cs" company="Microsoft">
3 // TODO: Update copyright text.
5 // -----------------------------------------------------------------------
7 using System.Collections.Specialized;
8 using System.Diagnostics;
9 using System.Diagnostics.Contracts;
12 using System.Runtime.Serialization;
13 using System.Threading.Tasks;
17 namespace Pithos.Network
20 using System.Collections.Generic;
25 /// TODO: Update summary.
27 public class RestClient:WebClient
29 public int Timeout { get; set; }
31 public bool TimedOut { get; set; }
33 public HttpStatusCode StatusCode { get; private set; }
35 public string StatusDescription { get; set; }
37 public long? RangeFrom { get; set; }
38 public long? RangeTo { get; set; }
40 public int Retries { get; set; }
42 private readonly Dictionary<string, string> _parameters=new Dictionary<string, string>();
43 public Dictionary<string, string> Parameters
47 Contract.Ensures(_parameters!=null);
52 private static readonly ILog Log = LogManager.GetLogger("RestClient");
55 [ContractInvariantMethod]
56 private void Invariants()
58 Contract.Invariant(Headers!=null);
61 public RestClient():base()
67 public RestClient(RestClient other)
71 throw new ArgumentNullException("other");
72 Contract.EndContractBlock();
75 Timeout = other.Timeout;
76 Retries = other.Retries;
77 BaseAddress = other.BaseAddress;
79 foreach (var parameter in other.Parameters)
81 Parameters.Add(parameter.Key,parameter.Value);
84 this.Proxy = other.Proxy;
88 protected override WebRequest GetWebRequest(Uri address)
91 var webRequest = base.GetWebRequest(address);
92 var request = (HttpWebRequest)webRequest;
93 if (IfModifiedSince.HasValue)
94 request.IfModifiedSince = IfModifiedSince.Value;
95 request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
97 request.Timeout = Timeout;
99 if (RangeFrom.HasValue)
101 if (RangeTo.HasValue)
102 request.AddRange(RangeFrom.Value, RangeTo.Value);
104 request.AddRange(RangeFrom.Value);
109 public DateTime? IfModifiedSince { get; set; }
111 //Asynchronous version
112 protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
114 Log.InfoFormat("ASYNC [{0}] {1}",request.Method, request.RequestUri);
115 HttpWebResponse response = null;
119 response = (HttpWebResponse)base.GetWebResponse(request, result);
121 catch (WebException exc)
123 if (!TryGetResponse(exc, out response))
127 StatusCode = response.StatusCode;
128 LastModified = response.LastModified;
129 StatusDescription = response.StatusDescription;
135 //Synchronous version
136 protected override WebResponse GetWebResponse(WebRequest request)
138 HttpWebResponse response = null;
141 response = (HttpWebResponse)base.GetWebResponse(request);
143 catch (WebException exc)
145 if (!TryGetResponse(exc, out response))
149 StatusCode = response.StatusCode;
150 LastModified = response.LastModified;
151 StatusDescription = response.StatusDescription;
155 private bool TryGetResponse(WebException exc, out HttpWebResponse response)
158 //Fail on empty response
159 if (exc.Response == null)
162 response = (exc.Response as HttpWebResponse);
163 //Succeed on allowed status codes
164 if (AllowedStatusCodes.Contains(response.StatusCode))
167 //Does the response have any content to log?
168 if (exc.Response.ContentLength > 0)
170 var content = LogContent(exc.Response);
171 Log.ErrorFormat(content);
176 private readonly List<HttpStatusCode> _allowedStatusCodes=new List<HttpStatusCode>{HttpStatusCode.NotModified};
178 public List<HttpStatusCode> AllowedStatusCodes
182 return _allowedStatusCodes;
186 public DateTime LastModified { get; private set; }
188 private static string LogContent(WebResponse webResponse)
190 if (webResponse == null)
191 throw new ArgumentNullException("webResponse");
192 Contract.EndContractBlock();
194 //The response stream must be copied to avoid affecting other code by disposing of the
195 //original response stream.
196 var stream = webResponse.GetResponseStream();
197 using(var memStream=new MemoryStream((int) stream.Length))
198 using (var reader = new StreamReader(memStream))
200 stream.CopyTo(memStream);
201 string content = reader.ReadToEnd();
203 stream.Seek(0,SeekOrigin.Begin);
208 public string DownloadStringWithRetry(string address,int retries=0)
212 throw new ArgumentNullException("address");
214 var actualAddress = GetActualAddress(address);
216 TraceStart("GET",actualAddress);
218 var actualRetries = (retries == 0) ? Retries : retries;
220 var uriString = String.Join("/", BaseAddress.TrimEnd('/'), actualAddress);
222 var task = Retry(() =>
224 var content = base.DownloadString(uriString);
226 if (StatusCode == HttpStatusCode.NoContent)
232 var result = task.Result;
236 public void Head(string address,int retries=0)
238 AllowedStatusCodes.Add(HttpStatusCode.NotFound);
239 RetryWithoutContent(address, retries, "HEAD");
242 public void PutWithRetry(string address, int retries = 0)
244 RetryWithoutContent(address, retries, "PUT");
247 public void DeleteWithRetry(string address,int retries=0)
249 RetryWithoutContent(address, retries, "DELETE");
252 public string GetHeaderValue(string headerName,bool optional=false)
254 if (this.ResponseHeaders==null)
255 throw new InvalidOperationException("ResponseHeaders are null");
256 Contract.EndContractBlock();
258 var values=this.ResponseHeaders.GetValues(headerName);
264 //A required header was not found
265 throw new WebException(String.Format("The {0} header is missing", headerName));
268 public void SetNonEmptyHeaderValue(string headerName, string value)
270 if (String.IsNullOrWhiteSpace(value))
272 Headers.Add(headerName,value);
275 private void RetryWithoutContent(string address, int retries, string method)
278 throw new ArgumentNullException("address");
280 var actualAddress = GetActualAddress(address);
281 var actualRetries = (retries == 0) ? Retries : retries;
283 var task = Retry(() =>
285 var uriString = String.Join("/",BaseAddress ,actualAddress);
286 var uri = new Uri(uriString);
287 var request = GetWebRequest(uri);
288 request.Method = method;
289 if (ResponseHeaders!=null)
290 ResponseHeaders.Clear();
292 TraceStart(method, uriString);
294 request.ContentLength = 0;
296 //Have to use try/finally instead of using here, because WebClient needs a valid WebResponse object
297 //in order to return response headers
298 var response = (HttpWebResponse)GetWebResponse(request);
301 LastModified = response.LastModified;
302 StatusCode = response.StatusCode;
303 StatusDescription = response.StatusDescription;
318 catch (AggregateException ex)
320 var exc = ex.InnerException;
321 if (exc is RetryException)
323 Log.ErrorFormat("[{0}] RETRY FAILED for {1} after {2} retries",method,address,retries);
327 Log.ErrorFormat("[{0}] FAILED for {1} with \n{2}", method, address, exc);
334 Log.ErrorFormat("[{0}] FAILED for {1} with \n{2}", method, address, ex);
339 private static void TraceStart(string method, string actualAddress)
341 Log.InfoFormat("[{0}] {1} {2}", method, DateTime.Now, actualAddress);
344 private string GetActualAddress(string address)
346 if (Parameters.Count == 0)
348 var addressBuilder=new StringBuilder(address);
351 foreach (var parameter in Parameters)
354 addressBuilder.AppendFormat("?{0}={1}", parameter.Key, parameter.Value);
356 addressBuilder.AppendFormat("&{0}={1}", parameter.Key, parameter.Value);
359 return addressBuilder.ToString();
362 public string DownloadStringWithRetry(Uri address,int retries=0)
365 throw new ArgumentNullException("address");
367 var actualRetries = (retries == 0) ? Retries : retries;
368 var task = Retry(() =>
370 var content = base.DownloadString(address);
372 if (StatusCode == HttpStatusCode.NoContent)
378 var result = task.Result;
384 /// Copies headers from another RestClient
386 /// <param name="source">The RestClient from which the headers are copied</param>
387 public void CopyHeaders(RestClient source)
390 throw new ArgumentNullException("source", "source can't be null");
391 Contract.EndContractBlock();
392 //The Headers getter initializes the property, it is never null
393 Contract.Assume(Headers!=null);
395 CopyHeaders(source.Headers,Headers);
399 /// Copies headers from one header collection to another
401 /// <param name="source">The source collection from which the headers are copied</param>
402 /// <param name="target">The target collection to which the headers are copied</param>
403 public static void CopyHeaders(WebHeaderCollection source,WebHeaderCollection target)
406 throw new ArgumentNullException("source", "source can't be null");
408 throw new ArgumentNullException("target", "target can't be null");
409 Contract.EndContractBlock();
411 for (int i = 0; i < source.Count; i++)
413 target.Add(source.GetKey(i), source[i]);
417 public void AssertStatusOK(string message)
419 if (StatusCode >= HttpStatusCode.BadRequest)
420 throw new WebException(String.Format("{0} with code {1} - {2}", message, StatusCode, StatusDescription));
424 private Task<T> Retry<T>(Func<T> original, int retryCount, TaskCompletionSource<T> tcs = null)
427 throw new ArgumentNullException("original");
428 Contract.EndContractBlock();
431 tcs = new TaskCompletionSource<T>();
432 Task.Factory.StartNew(original).ContinueWith(_original =>
434 if (!_original.IsFaulted)
435 tcs.SetFromTask(_original);
438 var e = _original.Exception.InnerException;
439 var we = (e as WebException);
444 var statusCode = GetStatusCode(we);
446 //Return null for 404
447 if (statusCode == HttpStatusCode.NotFound)
448 tcs.SetResult(default(T));
449 //Retry for timeouts and service unavailable
450 else if (we.Status == WebExceptionStatus.Timeout ||
451 (we.Status == WebExceptionStatus.ProtocolError && statusCode == HttpStatusCode.ServiceUnavailable))
456 Log.ErrorFormat("[ERROR] Timed out too many times. \n{0}\n",e);
457 tcs.SetException(new RetryException("Timed out too many times.", e));
462 "[RETRY] Timed out after {0} ms. Will retry {1} more times\n{2}", Timeout,
464 Retry(original, retryCount - 1, tcs);
475 private HttpStatusCode GetStatusCode(WebException we)
478 throw new ArgumentNullException("we");
479 var statusCode = HttpStatusCode.RequestTimeout;
480 if (we.Response != null)
482 statusCode = ((HttpWebResponse) we.Response).StatusCode;
483 this.StatusCode = statusCode;
488 public UriBuilder GetAddressBuilder(string container, string objectName)
490 var builder = new UriBuilder(String.Join("/", BaseAddress, container, objectName));
494 public Dictionary<string, string> GetMeta(string metaPrefix)
496 if (String.IsNullOrWhiteSpace(metaPrefix))
497 throw new ArgumentNullException("metaPrefix");
498 Contract.EndContractBlock();
500 var keys = ResponseHeaders.AllKeys.AsQueryable();
501 var dict = (from key in keys
502 where key.StartsWith(metaPrefix)
503 let name = key.Substring(metaPrefix.Length)
504 select new { Name = name, Value = ResponseHeaders[key] })
505 .ToDictionary(t => t.Name, t => t.Value);
510 public class RetryException:Exception
512 public RetryException()
518 public RetryException(string message)
524 public RetryException(string message,Exception innerException)
525 :base(message,innerException)
530 public RetryException(SerializationInfo info,StreamingContext context)