Skip to content

[OTLP] Synchronous requests for HTTP calls #6235

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#if NETFRAMEWORK
using System.Net.Http;
#endif
using System.Net;
using System.Net.Http.Headers;
using OpenTelemetry.Internal;

Expand Down Expand Up @@ -96,6 +97,37 @@ protected HttpRequestMessage CreateHttpRequest(byte[] buffer, int contentLength)
return request;
}

protected (Uri Uri, HttpMethod Method, Dictionary<string, string> Headers, byte[] Content, string ContentType)
CreateSynchronousRequestParams(byte[] buffer, int contentLength)
{
Uri uri = this.Endpoint;


HttpMethod method = HttpMethod.Post;

var headers = new Dictionary<string, string>();
foreach (var header in this.Headers)
{
headers[header.Key] = header.Value;
}


byte[] content;
if (contentLength < buffer.Length)
{
content = new byte[contentLength];
Array.Copy(buffer, 0, content, 0, contentLength);
}
else
{
content = buffer;
}

string contentType = this.MediaTypeHeader.ToString();

return (uri, method, headers, content, contentType);
}

protected HttpResponseMessage SendHttpRequest(HttpRequestMessage request, CancellationToken cancellationToken)
{
#if NET
Expand All @@ -108,4 +140,208 @@ protected HttpResponseMessage SendHttpRequest(HttpRequestMessage request, Cancel
return this.HttpClient.SendAsync(request, cancellationToken).GetAwaiter().GetResult();
#endif
}

protected HttpResponseMessage SendHttpRequestSynchronous(Uri uri, HttpMethod method, Dictionary<string, string> headers = null, byte[] content = null, string contentType = null, CancellationToken cancellationToken = default)
{
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = method.ToString();
webRequest.AllowAutoRedirect = true;

if (headers != null)
{
foreach (var header in headers)
{
if (WebHeaderCollection.IsRestricted(header.Key))
{
switch (header.Key.ToLowerInvariant())
{
case "accept":
webRequest.Accept = header.Value;
break;
case "connection":
webRequest.Connection = header.Value;
break;
case "content-type":
break;
case "user-agent":
webRequest.UserAgent = header.Value;
break;
case "content-length":
break;
case "expect":
webRequest.Expect = header.Value;
break;
case "date":
webRequest.Date = DateTime.Parse(header.Value);
break;
case "host":
break;
case "if-modified-since":
webRequest.IfModifiedSince = DateTime.Parse(header.Value);
break;
case "range":
string[] range = header.Value.Split('=', ',');
if (range.Length >= 2 && range[0].Trim().Equals("bytes"))
{
string[] startEnd = range[1].Split('-');
if (startEnd.Length >= 2)
{
long start = long.Parse(startEnd[0]);
long end = long.Parse(startEnd[1]);
webRequest.AddRange(start, end);
}
}
break;
case "referer":
webRequest.Referer = header.Value;
break;
case "transfer-encoding":
webRequest.TransferEncoding = header.Value;
break;
}
}
else
{
webRequest.Headers.Add(header.Key, header.Value);
}
}
}


if (!string.IsNullOrEmpty(contentType))
{
webRequest.ContentType = contentType;
}


if (content != null && content.Length > 0)
{
webRequest.ContentLength = content.Length;

using (var requestStream = webRequest.GetRequestStream())
{
requestStream.Write(content, 0, content.Length);
}
}
else
{
webRequest.ContentLength = 0;
}

cancellationToken.Register(webRequest.Abort);

try
{
using (var webResponse = (HttpWebResponse)webRequest.GetResponse())
{
return CreateResponseFromWebResponse(webResponse);
}
}
catch (WebException ex)
{
if (ex.Response is HttpWebResponse errorResponse)
{
return CreateResponseFromWebResponse(errorResponse);
}

// For cases where there's no response (timeout, etc.)
var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
ReasonPhrase = ex.Message,
};

return response;
}
catch (Exception ex)
{
var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
ReasonPhrase = ex.Message,
};

return response;
}
}

private static HttpResponseMessage CreateResponseFromWebResponse(HttpWebResponse webResponse)
{
var response = new HttpResponseMessage(webResponse.StatusCode)
{
ReasonPhrase = webResponse.StatusDescription,
Version = new Version(webResponse.ProtocolVersion.ToString()),
};

foreach (string headerName in webResponse.Headers.AllKeys)
{
if (headerName.Equals("Content-Length", StringComparison.OrdinalIgnoreCase) ||
headerName.Equals("Content-Type", StringComparison.OrdinalIgnoreCase) ||
headerName.Equals("Content-Encoding", StringComparison.OrdinalIgnoreCase) ||
headerName.Equals("Content-Language", StringComparison.OrdinalIgnoreCase) ||
headerName.Equals("Content-Location", StringComparison.OrdinalIgnoreCase) ||
headerName.Equals("Content-MD5", StringComparison.OrdinalIgnoreCase) ||
headerName.Equals("Content-Range", StringComparison.OrdinalIgnoreCase) ||
headerName.Equals("Content-Disposition", StringComparison.OrdinalIgnoreCase))
{
continue;
}

response.Headers.TryAddWithoutValidation(headerName, webResponse.Headers[headerName]);
}


if (webResponse.ContentLength != 0)
{
var responseStream = webResponse.GetResponseStream();
var memoryStream = new MemoryStream();

if (responseStream != null)
{
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
{
memoryStream.Write(buffer, 0, bytesRead);
}

memoryStream.Position = 0;
}

response.Content = new ByteArrayContent(memoryStream.ToArray());

if (!string.IsNullOrEmpty(webResponse.ContentType))
{
response.Content.Headers.ContentType = new MediaTypeHeaderValue(webResponse.ContentType);
}

if (webResponse.ContentLength > 0)
{
response.Content.Headers.ContentLength = webResponse.ContentLength;
}

var contentEncoding = webResponse.Headers["Content-Encoding"];
if (!string.IsNullOrEmpty(contentEncoding))
{
response.Content.Headers.TryAddWithoutValidation("Content-Encoding", contentEncoding);
}

var contentLanguage = webResponse.Headers["Content-Language"];
if (!string.IsNullOrEmpty(contentLanguage))
{
response.Content.Headers.TryAddWithoutValidation("Content-Language", contentLanguage);
}

// Add other content headers if needed
var contentDisposition = webResponse.Headers["Content-Disposition"];
if (!string.IsNullOrEmpty(contentDisposition))
{
response.Content.Headers.TryAddWithoutValidation("Content-Disposition", contentDisposition);
}
}
else
{
response.Content = new ByteArrayContent([]);
}

return response;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,16 @@ public override ExportClientResponse SendExportRequest(byte[] buffer, int conten
{
try
{
using var httpRequest = this.CreateHttpRequest(buffer, contentLength);
#if NET
var httpRequest = this.CreateHttpRequest(buffer, contentLength);
using var httpResponse = this.SendHttpRequest(httpRequest, cancellationToken);

#else
var httpRequest = this.CreateSynchronousRequestParams(buffer, contentLength);
using var httpResponse = this.SendHttpRequestSynchronous(httpRequest.Uri, httpRequest.Method, httpRequest.Headers, httpRequest.Content, httpRequest.ContentType, cancellationToken);

#endif

try
{
httpResponse.EnsureSuccessStatusCode();
Expand Down