public void ProcessCallbackMessage(SerializableHttpRequestMessage message) { if (message != null) { this.HandleIncomingEvents?.Invoke(this, new EventsChannelArgs(message)); } }
public async Task Post(HttpRequestMessage request) { // CallbackController can't implement IEventChannel as ASP.Net creates new instance of the // controller everytime a new request is received. var message = new SerializableHttpRequestMessage(); await message.InitializeAsync(request, null).ConfigureAwait(false); // Pass down the response to event channel WebEventChannel.Instance.HandleIncomingHttpRequest(message); }
public async Task <HttpResponseMessage> PostAsync() { Logger.Instance.Information("AuthHeader: " + this.Request.Headers.Authorization.Parameter); var httpmessage = new SerializableHttpRequestMessage(); CallbackContext callbackContext = null; var loggingContext = this.Request.Properties[Constants.LoggingContext] as LoggingContext; bool isIncomingNewInvitation = !this.Request.Properties.ContainsKey(Constants.CallbackContext); if (!isIncomingNewInvitation) { callbackContext = this.Request.Properties[Constants.CallbackContext] as CallbackContext; } else { //support incoming invite Logger.Instance.Information("New incoming invite get, process locally!"); callbackContext = new CallbackContext(); } try { await httpmessage.InitializeAsync(this.Request, loggingContext.TrackingId.ToString(), true).ConfigureAwait(false); httpmessage.LoggingContext = loggingContext; m_eventChannel.ProcessCallbackMessage(httpmessage); } catch (Exception ex) { Logger.Instance.Error(ex, "Fail to parse incoming http message"); return(CreateHttpResponse(HttpStatusCode.InternalServerError, loggingContext, "{\"Error\":\"Internal error occured.!\"}")); } //This is NOT the initial incoming INVITE message. if (isIncomingNewInvitation) { EventResponse responseBody = new EventResponse() { CallbackContext = JsonConvert.SerializeObject(callbackContext) }; string jsonContent = JsonConvert.SerializeObject(responseBody); return(CreateHttpResponse(HttpStatusCode.OK, loggingContext, jsonContent)); } else { return(CreateHttpResponse(HttpStatusCode.OK, loggingContext)); } }
/// <summary> /// The action when receive callback. /// </summary> /// <returns>The task.</returns> private void OnReceivedCallback(object sender, EventsChannelArgs events) { SerializableHttpRequestMessage httpMessage = events.CallbackHttpRequest; if (httpMessage == null) { return; } if (Logger.Instance.HttpRequestResponseNeedsToBeLogged) { //Technically we should not wait a task here. However, this is in event channel call back thread, and we should not use async in event channel handler LogHelper.LogProtocolHttpRequestAsync(httpMessage, httpMessage.LoggingContext != null ? httpMessage.LoggingContext.TrackingId.ToString() : string.Empty, true).Wait(1000); } EventsEntity eventsEntity = null; using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(httpMessage.Content))) { MediaTypeHeaderValue typeHeader = null; MediaTypeHeaderValue.TryParse(httpMessage.ContentType, out typeHeader); if (typeHeader != null) { try { eventsEntity = MediaTypeFormattersHelper.ReadContentWithType(typeof(EventsEntity), typeHeader, stream) as EventsEntity; } catch (Exception ex) { Logger.Instance.Error(ex, "exception happened in deserialzie http message to EventsEntity"); return; } } else { Logger.Instance.Error("Invalid type header in callback message, skip this message! type header value: " + httpMessage.ContentType); return; } } if (eventsEntity != null && eventsEntity.Senders != null && eventsEntity.Senders.Count > 0) //Ignore heartbeat events or call back reachability check events { this.ProcessEvents(new EventsChannelContext(eventsEntity, httpMessage.LoggingContext)); } }
public static async Task LogHttpRequestAsync(this Logger logger, HttpRequestMessage request, string requestId, bool isIncomingRequest) { var sb = new StringBuilder(); try { var myRequest = new SerializableHttpRequestMessage(); await myRequest.InitializeAsync(request, requestId, isIncomingRequest).ConfigureAwait(false); string logString = await myRequest.GetLogStringAsync().ConfigureAwait(false); logger.Information(logString); } catch (Exception ex) { logger.Warning("Log http request failed. Ex: " + ex.ToString()); } }
public static EventsChannelArgs GetEventsChannelArgsFromContent(string jsonContent) { var request = new HttpRequestMessage(); request.Method = HttpMethod.Post; request.RequestUri = new Uri("https://platformservicemonitoring3.cloudapp.net/callback?callbackContext={\"JobId\":\"5474606859144360bc7cee5a87d9e9cc\"%2c\"InstanceId\":\"133976f272274227bc45e349c2aac558\"}"); if (!TestHelper.IsInternalApp) { jsonContent = jsonContent.Replace(Constants.DefaultResourceNamespace, Constants.PublicServiceResourceNamespace); } request.Content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); var message = new SerializableHttpRequestMessage(); message.InitializeAsync(request, "no-request-id").Wait(); return(new EventsChannelArgs(message)); }
/// <summary> /// ProcessCallbackMessage /// </summary> /// <param name="message"></param> private void ProcessCallbackMessage(string message) { Logger.Instance.Information("ProcessCallbackMessage start!"); SerializableHttpRequestMessage httpMessage = null; try { httpMessage = JsonConvert.DeserializeObject <SerializableHttpRequestMessage>(message); } catch (Exception ex) { Logger.Instance.Error(ex, "exception happened in deserialzie http message"); return; } if (httpMessage != null) { this.HandleIncomingEvents?.Invoke(this, new EventsChannelArgs(httpMessage)); } }
/// <summary> /// Handles the http request received through Trouter /// </summary> /// <param name="requestReceived">Http request to be processed</param> /// <returns><see cref="HttpResponseMessage"/> to be sent in response of the request</returns> private async Task <HttpResponseMessage> ProcessIncomingTrouterRequestAsync(RequestReceived requestReceived) { try { m_logger.Information("Incoming callback\r\n " + requestReceived.Body); var message = new SerializableHttpRequestMessage(); message.Method = requestReceived.HttpMethod; message.Uri = requestReceived.RelativeUri; message.LoggingContext = new LoggingContext(Guid.NewGuid()); message.Content = requestReceived.Body; message.ContentType = "application/json"; message.IsIncoming = true; message.Timestamp = DateTime.UtcNow; if (requestReceived.Headers != null) { message.RequestHeaders = new List <Tuple <string, string> >(); foreach (KeyValuePair <string, string> header in requestReceived.Headers) { if (!string.IsNullOrEmpty(header.Key) && !string.IsNullOrEmpty(header.Value)) { message.RequestHeaders.Add(new Tuple <string, string>(header.Key, header.Value)); } } } // Suppress the warning await Task.CompletedTask.ConfigureAwait(false); // Pass down the response to event channel HandleIncomingEvents?.Invoke(this, new EventsChannelArgs(message)); } catch (Exception ex) { Debug.Assert(false, "unexpected exception: " + ex.ToString()); } return(new HttpResponseMessage(HttpStatusCode.OK)); }
public EventsChannelArgs(SerializableHttpRequestMessage request) { this.CallbackHttpRequest = request; }
public void HandleIncomingHttpRequest(SerializableHttpRequestMessage message) { HandleIncomingEvents?.Invoke(Instance, new EventsChannelArgs(message)); }
public async Task <HttpResponseMessage> PostAsync() { var httpmessage = new SerializableHttpRequestMessage(); string serializedMessage = null; CallbackContext callbackContext = null; var loggingContext = this.Request.Properties[Constants.LoggingContext] as LoggingContext; bool isIncomingNewInvitation = !this.Request.Properties.ContainsKey(Constants.CallbackContext); if (!isIncomingNewInvitation) { callbackContext = this.Request.Properties[Constants.CallbackContext] as CallbackContext; } else { //support incoming invite Logger.Instance.Information("New incoming invite get, process locally!"); callbackContext = new CallbackContext(); callbackContext.InstanceId = WebApiApplication.InstanceId; } try { await httpmessage.InitializeAsync(this.Request, loggingContext.TrackingId.ToString(), true).ConfigureAwait(false); httpmessage.LoggingContext = loggingContext; } catch (Exception ex) { Logger.Instance.Error(ex, "Fail to parse incoming http message"); return(CreateHttpResponse(HttpStatusCode.InternalServerError, loggingContext, "{\"Error\":\"Internal error occured.!\"}")); } if (callbackContext.InstanceId == null) { //In future, we need to support incoming invite, and should not return error here return(CreateHttpResponse(HttpStatusCode.BadRequest, loggingContext, "{\"Error\":\"No or invalid callback context specified!\"}")); } else { serializedMessage = JsonConvert.SerializeObject(httpmessage); try { await m_callbackQueue.SaveCallbackMessageAsync(callbackContext.InstanceId, serializedMessage).ConfigureAwait(false); //This is NOT the initial incoming INVITE message. if (isIncomingNewInvitation) { EventResponse responseBody = new EventResponse() { CallbackContext = JsonConvert.SerializeObject(callbackContext) }; string jsonContent = JsonConvert.SerializeObject(responseBody); return(CreateHttpResponse(HttpStatusCode.OK, loggingContext, jsonContent)); } else { return(CreateHttpResponse(HttpStatusCode.OK, loggingContext)); } } catch (PlatformServiceAzureStorageException) { return(CreateHttpResponse(HttpStatusCode.InternalServerError, loggingContext)); } } }