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 private WebHeaderCollection _responseHeaders;
90 public new WebHeaderCollection ResponseHeaders
94 if (base.ResponseHeaders==null)
96 return _responseHeaders;
100 _responseHeaders = null;
101 return base.ResponseHeaders;
106 set { _responseHeaders = value; }
108 protected override WebRequest GetWebRequest(Uri address)
111 var webRequest = base.GetWebRequest(address);
112 var request = (HttpWebRequest)webRequest;
113 if (IfModifiedSince.HasValue)
114 request.IfModifiedSince = IfModifiedSince.Value;
115 request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
117 request.Timeout = Timeout;
119 if (RangeFrom.HasValue)
121 if (RangeTo.HasValue)
122 request.AddRange(RangeFrom.Value, RangeTo.Value);
124 request.AddRange(RangeFrom.Value);
129 public DateTime? IfModifiedSince { get; set; }
131 //Asynchronous version
132 protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
134 Log.InfoFormat("ASYNC [{0}] {1}",request.Method, request.RequestUri);
135 HttpWebResponse response = null;
139 response = (HttpWebResponse)base.GetWebResponse(request, result);
141 catch (WebException exc)
143 if (!TryGetResponse(exc, out response))
147 StatusCode = response.StatusCode;
148 LastModified = response.LastModified;
149 StatusDescription = response.StatusDescription;
155 //Synchronous version
156 protected override WebResponse GetWebResponse(WebRequest request)
158 HttpWebResponse response = null;
161 response = (HttpWebResponse)base.GetWebResponse(request);
163 catch (WebException exc)
165 if (!TryGetResponse(exc, out response))
169 StatusCode = response.StatusCode;
170 LastModified = response.LastModified;
171 StatusDescription = response.StatusDescription;
175 private bool TryGetResponse(WebException exc, out HttpWebResponse response)
178 //Fail on empty response
179 if (exc.Response == null)
182 response = (exc.Response as HttpWebResponse);
183 //Succeed on allowed status codes
184 if (AllowedStatusCodes.Contains(response.StatusCode))
187 //Does the response have any content to log?
188 if (exc.Response.ContentLength > 0)
190 var content = GetContent(exc.Response);
191 Log.ErrorFormat(content);
196 private readonly List<HttpStatusCode> _allowedStatusCodes=new List<HttpStatusCode>{HttpStatusCode.NotModified};
198 public List<HttpStatusCode> AllowedStatusCodes
202 return _allowedStatusCodes;
206 public DateTime LastModified { get; private set; }
208 private static string GetContent(WebResponse webResponse)
210 if (webResponse == null)
211 throw new ArgumentNullException("webResponse");
212 Contract.EndContractBlock();
215 using (var stream = webResponse.GetResponseStream())
216 using (var reader = new StreamReader(stream))
218 content = reader.ReadToEnd();
223 public string DownloadStringWithRetry(string address,int retries=0)
227 throw new ArgumentNullException("address");
229 var actualAddress = GetActualAddress(address);
231 TraceStart("GET",actualAddress);
233 var actualRetries = (retries == 0) ? Retries : retries;
236 var task = Retry(() =>
238 var uriString = String.Join("/", BaseAddress.TrimEnd('/'), actualAddress);
239 var content = base.DownloadString(uriString);
241 if (StatusCode == HttpStatusCode.NoContent)
247 var result = task.Result;
251 public void Head(string address,int retries=0)
253 AllowedStatusCodes.Add(HttpStatusCode.NotFound);
254 RetryWithoutContent(address, retries, "HEAD");
257 public void PutWithRetry(string address, int retries = 0)
259 RetryWithoutContent(address, retries, "PUT");
262 public void DeleteWithRetry(string address,int retries=0)
264 RetryWithoutContent(address, retries, "DELETE");
267 public string GetHeaderValue(string headerName,bool optional=false)
269 if (this.ResponseHeaders==null)
270 throw new InvalidOperationException("ResponseHeaders are null");
271 Contract.EndContractBlock();
273 var values=this.ResponseHeaders.GetValues(headerName);
279 //A required header was not found
280 throw new WebException(String.Format("The {0} header is missing", headerName));
283 public void SetNonEmptyHeaderValue(string headerName, string value)
285 if (String.IsNullOrWhiteSpace(value))
287 Headers.Add(headerName,value);
290 private void RetryWithoutContent(string address, int retries, string method)
293 throw new ArgumentNullException("address");
295 var actualAddress = GetActualAddress(address);
296 var actualRetries = (retries == 0) ? Retries : retries;
298 var task = Retry(() =>
300 var uriString = String.Join("/",BaseAddress ,actualAddress);
301 var uri = new Uri(uriString);
302 var request = GetWebRequest(uri);
303 request.Method = method;
304 if (ResponseHeaders!=null)
305 ResponseHeaders.Clear();
307 TraceStart(method, uriString);
309 request.ContentLength = 0;
311 var response = (HttpWebResponse)GetWebResponse(request);
312 //var response = (HttpWebResponse)request.GetResponse();
314 //ResponseHeaders= response.Headers;
316 LastModified = response.LastModified;
317 StatusCode = response.StatusCode;
318 StatusDescription = response.StatusDescription;
328 catch (AggregateException ex)
330 var exc = ex.InnerException;
331 if (exc is RetryException)
333 Log.ErrorFormat("[{0}] RETRY FAILED for {1} after {2} retries",method,address,retries);
337 Log.ErrorFormat("[{0}] FAILED for {1} with \n{2}", method, address, exc);
344 Log.ErrorFormat("[{0}] FAILED for {1} with \n{2}", method, address, ex);
349 private static void TraceStart(string method, string actualAddress)
351 Log.InfoFormat("[{0}] {1} {2}", method, DateTime.Now, actualAddress);
354 private string GetActualAddress(string address)
356 if (Parameters.Count == 0)
358 var addressBuilder=new StringBuilder(address);
361 foreach (var parameter in Parameters)
364 addressBuilder.AppendFormat("?{0}={1}", parameter.Key, parameter.Value);
366 addressBuilder.AppendFormat("&{0}={1}", parameter.Key, parameter.Value);
369 return addressBuilder.ToString();
372 public string DownloadStringWithRetry(Uri address,int retries=0)
375 throw new ArgumentNullException("address");
377 var actualRetries = (retries == 0) ? Retries : retries;
378 var task = Retry(() =>
380 var content = base.DownloadString(address);
382 if (StatusCode == HttpStatusCode.NoContent)
388 var result = task.Result;
394 /// Copies headers from another RestClient
396 /// <param name="source">The RestClient from which the headers are copied</param>
397 public void CopyHeaders(RestClient source)
400 throw new ArgumentNullException("source", "source can't be null");
401 Contract.EndContractBlock();
402 //The Headers getter initializes the property, it is never null
403 Contract.Assume(Headers!=null);
405 CopyHeaders(source.Headers,Headers);
409 /// Copies headers from one header collection to another
411 /// <param name="source">The source collection from which the headers are copied</param>
412 /// <param name="target">The target collection to which the headers are copied</param>
413 public static void CopyHeaders(WebHeaderCollection source,WebHeaderCollection target)
416 throw new ArgumentNullException("source", "source can't be null");
418 throw new ArgumentNullException("target", "target can't be null");
419 Contract.EndContractBlock();
421 for (int i = 0; i < source.Count; i++)
423 target.Add(source.GetKey(i), source[i]);
427 public void AssertStatusOK(string message)
429 if (StatusCode >= HttpStatusCode.BadRequest)
430 throw new WebException(String.Format("{0} with code {1} - {2}", message, StatusCode, StatusDescription));
434 private Task<T> Retry<T>(Func<T> original, int retryCount, TaskCompletionSource<T> tcs = null)
437 throw new ArgumentNullException("original");
438 Contract.EndContractBlock();
441 tcs = new TaskCompletionSource<T>();
442 Task.Factory.StartNew(original).ContinueWith(_original =>
444 if (!_original.IsFaulted)
445 tcs.SetFromTask(_original);
448 var e = _original.Exception.InnerException;
449 var we = (e as WebException);
454 var statusCode = GetStatusCode(we);
456 //Return null for 404
457 if (statusCode == HttpStatusCode.NotFound)
458 tcs.SetResult(default(T));
459 //Retry for timeouts and service unavailable
460 else if (we.Status == WebExceptionStatus.Timeout ||
461 (we.Status == WebExceptionStatus.ProtocolError && statusCode == HttpStatusCode.ServiceUnavailable))
466 Log.ErrorFormat("[ERROR] Timed out too many times. \n{0}\n",e);
467 tcs.SetException(new RetryException("Timed out too many times.", e));
472 "[RETRY] Timed out after {0} ms. Will retry {1} more times\n{2}", Timeout,
474 Retry(original, retryCount - 1, tcs);
485 private HttpStatusCode GetStatusCode(WebException we)
488 throw new ArgumentNullException("we");
489 var statusCode = HttpStatusCode.RequestTimeout;
490 if (we.Response != null)
492 statusCode = ((HttpWebResponse) we.Response).StatusCode;
493 this.StatusCode = statusCode;
498 public UriBuilder GetAddressBuilder(string container, string objectName)
500 var builder = new UriBuilder(String.Join("/", BaseAddress, container, objectName));
504 public Dictionary<string, string> GetMeta(string metaPrefix)
506 if (String.IsNullOrWhiteSpace(metaPrefix))
507 throw new ArgumentNullException("metaPrefix");
508 Contract.EndContractBlock();
510 var keys = ResponseHeaders.AllKeys.AsQueryable();
511 var dict = (from key in keys
512 where key.StartsWith(metaPrefix)
513 let name = key.Substring(metaPrefix.Length)
514 select new { Name = name, Value = ResponseHeaders[key] })
515 .ToDictionary(t => t.Name, t => t.Value);
520 public class RetryException:Exception
522 public RetryException()
528 public RetryException(string message)
534 public RetryException(string message,Exception innerException)
535 :base(message,innerException)
540 public RetryException(SerializationInfo info,StreamingContext context)