Skip to content

Commit

Permalink
Merge pull request #150 from MaceWindu/error-handling
Browse files Browse the repository at this point in the history
Small QoL improvements around WebSocket connection
  • Loading branch information
Sicos1977 committed Apr 3, 2024
2 parents 48fbc43 + 548c63a commit 084d724
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 7 deletions.
4 changes: 2 additions & 2 deletions ChromiumHtmlToPdfLib/Browser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -695,7 +695,7 @@ public async Task RunJavascriptAsync(string script, CancellationToken cancellati

var printToPdfResponse = PrintToPdfResponse.FromJson(result);

if (string.IsNullOrEmpty(printToPdfResponse.Result.Stream))
if (printToPdfResponse.Error != null || string.IsNullOrEmpty(printToPdfResponse.Result?.Stream))
throw new ConversionException($"Conversion failed ... did not get the expected response from Chromium, response '{result}'");

if (!outputStream.CanWrite)
Expand All @@ -704,7 +704,7 @@ public async Task RunJavascriptAsync(string script, CancellationToken cancellati
_logger?.Info("Resetting output stream to position 0");

message = new Message { Method = "IO.read" };
message.AddParameter("handle", printToPdfResponse.Result.Stream!);
message.AddParameter("handle", printToPdfResponse.Result!.Stream!);
message.AddParameter("size", 1048576); // Get the pdf in chunks of 1MB

_logger?.Info("Reading generated PDF from IO stream with handle id {stream}", printToPdfResponse.Result.Stream);
Expand Down
15 changes: 13 additions & 2 deletions ChromiumHtmlToPdfLib/Connection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,11 @@ public class Connection : IDisposable, IAsyncDisposable
/// </summary>
private readonly int _timeout;

/// <summary>
/// Task to await for <see cref="ReceiveLoop"/> completion.
/// </summary>
private readonly Task<Task> _receiveTask;

/// <summary>
/// Keeps track is we already disposed our resources
/// </summary>
Expand All @@ -114,7 +119,7 @@ internal Connection(string url, int timeout, Logger? logger)
_webSocket = new ClientWebSocket();
_receiveLoopCts = new CancellationTokenSource();
OpenWebSocketAsync().GetAwaiter().GetResult();
Task.Factory.StartNew(ReceiveLoop, new ReceiveLoopState(_logger, _webSocket, OnMessageReceived, _receiveLoopCts.Token), _receiveLoopCts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
_receiveTask = Task.Factory.StartNew(ReceiveLoop, new ReceiveLoopState(_logger, _webSocket, OnMessageReceived, _receiveLoopCts.Token), _receiveLoopCts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
#endregion

Expand Down Expand Up @@ -160,6 +165,10 @@ private static async Task ReceiveLoop(object? stateData)
{
// Ignore
}
catch (WebSocketException wsex) when (wsex.Message == "The remote party closed the WebSocket connection without completing the close handshake.")
{
// Ignore
}
catch (Exception exception)
{
WebSocketOnError(state.Logger, new ErrorEventArgs(exception));
Expand Down Expand Up @@ -333,6 +342,8 @@ public async Task InternalDisposeAsync()

_receiveLoopCts.Cancel();

await (await _receiveTask.ConfigureAwait(false)).ConfigureAwait(false);

_logger?.Info("Disposing websocket connection to url '{url}'", _url);

if (_webSocket.State == WebSocketState.Open)
Expand All @@ -346,7 +357,7 @@ public async Task InternalDisposeAsync()
}
catch (Exception exception)
{
_logger?.Error("An error occurred while closing the web socket, error: '{error}'", ExceptionHelpers.GetInnerException(exception));
_logger?.Error(exception, "An error occurred while closing the web socket, error: '{error}'", ExceptionHelpers.GetInnerException(exception));
}

_logger?.Info("Websocket connection closed");
Expand Down
35 changes: 32 additions & 3 deletions ChromiumHtmlToPdfLib/Protocol/PrintToPdfResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,25 @@ namespace ChromiumHtmlToPdfLib.Protocol;
internal class PrintToPdfResponse
{
#region Properties
[JsonProperty("id")]
public int Id { get; set; }

/// <summary>
/// <see cref="PrintToPdfResult" />
/// </summary>
[JsonProperty("result")]
public PrintToPdfResult Result { get; set; } = null!;
public PrintToPdfResult? Result { get; set; }

/// <summary>
/// <see cref="PrintToPdfErrorResult" />
/// </summary>
[JsonProperty("error")]
public PrintToPdfErrorResult? Error { get; set; }

/// <summary>
/// Returns <see cref="PrintToPdfResult.Data" /> as array of bytes
/// </summary>
public byte[] Bytes => Convert.FromBase64String(Result.Data);
public byte[]? Bytes => Result != null ? Convert.FromBase64String(Result.Data) : null;
#endregion

#region FromJson
Expand Down Expand Up @@ -78,4 +87,24 @@ internal class PrintToPdfResult
[JsonProperty("stream")]
public string? Stream { get; set; }
#endregion
}
}

/// <summary>
/// Error result returned from the <see cref="Converter" /> ConvertToPdf method
/// </summary>
internal class PrintToPdfErrorResult
{
#region Properties
/// <summary>
/// Error code
/// </summary>
[JsonProperty("code")]
public int Code { get; set; }

/// <summary>
/// Error message
/// </summary>
[JsonProperty("message")]
public string? Message { get; set; }
#endregion
}

0 comments on commit 084d724

Please sign in to comment.