Skip to content

Commit

Permalink
chore: move channels into impl classes (#2794)
Browse files Browse the repository at this point in the history
  • Loading branch information
mxschmitt authored Dec 11, 2023
1 parent fe7542a commit ba2e378
Show file tree
Hide file tree
Showing 56 changed files with 1,642 additions and 3,252 deletions.
44 changes: 33 additions & 11 deletions src/Playwright/Core/APIRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,12 @@
* SOFTWARE.
*/

using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.Playwright.Helpers;
using Microsoft.Playwright.Transport.Channels;

namespace Microsoft.Playwright.Core;

Expand All @@ -37,17 +42,34 @@ public APIRequest(PlaywrightImpl playwright)

async Task<IAPIRequestContext> IAPIRequest.NewContextAsync(APIRequestNewContextOptions options)
{
var context = await _playwright._channel.NewRequestAsync(
options?.BaseURL,
options?.UserAgent,
options?.IgnoreHTTPSErrors,
options?.ExtraHTTPHeaders,
options?.HttpCredentials,
options?.Proxy,
options?.Timeout,
options?.StorageState,
options?.StorageStatePath)
.ConfigureAwait(false);
var args = new Dictionary<string, object>()
{
["baseURL"] = options?.BaseURL,
["userAgent"] = options?.UserAgent,
["ignoreHTTPSErrors"] = options?.IgnoreHTTPSErrors,
["extraHTTPHeaders"] = options?.ExtraHTTPHeaders?.ToProtocol(),
["httpCredentials"] = options?.HttpCredentials,
["proxy"] = options?.Proxy,
["timeout"] = options?.Timeout,
};
string storageState = options?.StorageState;
if (!string.IsNullOrEmpty(options?.StorageStatePath))
{
if (!File.Exists(options?.StorageStatePath))
{
throw new PlaywrightException($"The specified storage state file does not exist: {options?.StorageStatePath}");
}

storageState = File.ReadAllText(options?.StorageStatePath);
}
if (!string.IsNullOrEmpty(storageState))
{
args.Add("storageState", JsonSerializer.Deserialize<StorageState>(storageState, Helpers.JsonExtensions.DefaultJsonSerializerOptions));
}

var context = (await _playwright.SendMessageToServerAsync<APIRequestContextChannel>(
"newRequest",
args).ConfigureAwait(false)).Object;
context._request = this;
return context;
}
Expand Down
35 changes: 20 additions & 15 deletions src/Playwright/Core/APIRequestContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public APIRequestContext(IChannelOwner parent, string guid, APIRequestContextIni
IChannel<APIRequestContext> IChannelOwner<APIRequestContext>.Channel => _channel;

[MethodImpl(MethodImplOptions.NoInlining)]
public ValueTask DisposeAsync() => new(_channel.DisposeAsync());
public ValueTask DisposeAsync() => new(SendMessageToServerAsync("dispose"));

[MethodImpl(MethodImplOptions.NoInlining)]
public Task<IAPIResponse> FetchAsync(IRequest request, APIRequestContextOptions options = null)
Expand Down Expand Up @@ -121,19 +121,24 @@ public async Task<IAPIResponse> FetchAsync(string url, APIRequestContextOptions
jsonData = JsonSerializer.Serialize(options.DataObject, _connection.DefaultJsonSerializerOptionsKeepNulls);
}

return await _channel.FetchAsync(
url,
queryParams,
options.Method,
options.Headers,
jsonData,
postData,
(FormData)options.Form,
(FormData)options.Multipart,
options.Timeout,
options?.FailOnStatusCode,
options?.IgnoreHTTPSErrors,
options?.MaxRedirects).ConfigureAwait(false);
var message = new Dictionary<string, object>
{
["url"] = url,
["method"] = options?.Method,
["failOnStatusCode"] = options?.FailOnStatusCode,
["ignoreHTTPSErrors"] = options?.IgnoreHTTPSErrors,
["maxRedirects"] = options?.MaxRedirects,
["timeout"] = options.Timeout,
["params"] = queryParams?.ToProtocol(),
["headers"] = options.Headers?.ToProtocol(),
["jsonData"] = jsonData,
["postData"] = postData != null ? Convert.ToBase64String(postData) : null,
["formData"] = ((FormData)options.Form)?.ToProtocol(throwWhenSerializingFilePayloads: true),
["multipartData"] = ((FormData)options.Multipart)?.ToProtocol(),
};

var response = await SendMessageToServerAsync("fetch", message).ConfigureAwait(false);
return new APIResponse(this, response?.GetProperty("response").ToObject<Transport.Protocol.APIResponse>());
}

private bool IsJsonContentType(IDictionary<string, string> headers)
Expand Down Expand Up @@ -193,7 +198,7 @@ private APIRequestContextOptions WithMethod(APIRequestContextOptions options, st
public async Task<string> StorageStateAsync(APIRequestContextStorageStateOptions options = null)
{
string state = JsonSerializer.Serialize(
await _channel.StorageStateAsync().ConfigureAwait(false),
await SendMessageToServerAsync<StorageState>("storageState").ConfigureAwait(false),
JsonExtensions.DefaultJsonSerializerOptions);

if (!string.IsNullOrEmpty(options?.Path))
Expand Down
17 changes: 11 additions & 6 deletions src/Playwright/Core/APIResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.Playwright.Helpers;

namespace Microsoft.Playwright.Core;

Expand Down Expand Up @@ -61,12 +62,12 @@ public async Task<byte[]> BodyAsync()
{
try
{
var result = await _context._channel.FetchResponseBodyAsync(FetchUid()).ConfigureAwait(false);
if (result == null)
var response = await _context.SendMessageToServerAsync("fetchResponseBody", new Dictionary<string, object> { ["fetchUid"] = FetchUid() }).ConfigureAwait(false);
if (response?.TryGetProperty("binary", out var binary) == true)
{
throw new PlaywrightException("Response has been disposed");
return Convert.FromBase64String(binary.ToString());
}
return Convert.FromBase64String(result);
throw new PlaywrightException("Response has been disposed");
}
catch (Exception e) when (DriverMessages.IsTargetClosedError(e))
{
Expand All @@ -86,9 +87,13 @@ public async Task<string> TextAsync()

internal string FetchUid() => _initializer.FetchUid;

internal Task<string[]> FetchLogAsync() => _context._channel.FetchResponseLogAsync(FetchUid());
internal async Task<string[]> FetchLogAsync()
{
var response = await _context.SendMessageToServerAsync("fetchLog", new Dictionary<string, object> { ["fetchUid"] = FetchUid() }).ConfigureAwait(false);
return response.Value.GetProperty("log").ToObject<string[]>();
}

public ValueTask DisposeAsync() => new(_context._channel.DisposeAPIResponseAsync(FetchUid()));
public ValueTask DisposeAsync() => new(_context.SendMessageToServerAsync("disposeAPIResponse", new Dictionary<string, object> { ["fetchUid"] = FetchUid() }));

public override string ToString()
{
Expand Down
13 changes: 11 additions & 2 deletions src/Playwright/Core/Accessibility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
* SOFTWARE.
*/

using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.Playwright.Transport.Channels;
Expand All @@ -37,9 +38,17 @@ public Accessibility(PageChannel channel)
_channel = channel;
}

public Task<JsonElement?> SnapshotAsync(AccessibilitySnapshotOptions options = default)
public async Task<JsonElement?> SnapshotAsync(AccessibilitySnapshotOptions options = default)
{
options ??= new();
return _channel.AccessibilitySnapshotAsync(options.InterestingOnly, (options.Root as ElementHandle)?.ElementChannel);
if ((await _channel.Object.SendMessageToServerAsync("accessibilitySnapshot", new Dictionary<string, object>
{
["interestingOnly"] = options?.InterestingOnly,
["root"] = (options.Root as ElementHandle)?.ElementChannel,
}).ConfigureAwait(false)).Value.TryGetProperty("rootAXNode", out var jsonElement))
{
return jsonElement;
}
return null;
}
}
28 changes: 20 additions & 8 deletions src/Playwright/Core/Artifact.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,12 @@
* SOFTWARE.
*/

using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.Playwright.Helpers;
using Microsoft.Playwright.Transport;
using Microsoft.Playwright.Transport.Channels;
using Microsoft.Playwright.Transport.Protocol;
Expand Down Expand Up @@ -56,19 +59,26 @@ public async Task<string> PathAfterFinishedAsync()
{
throw new PlaywrightException("Path is not available when connecting remotely. Use SaveAsAsync() to save a local copy.");
}
return await _channel.PathAfterFinishedAsync().ConfigureAwait(false);
return (await SendMessageToServerAsync<JsonElement?>("pathAfterFinished")
.ConfigureAwait(false)).GetString("value", true);
}

[MethodImpl(MethodImplOptions.NoInlining)]
public async Task SaveAsAsync(string path)
{
if (!_connection.IsRemote)
{
await _channel.SaveAsAsync(path).ConfigureAwait(false);
await SendMessageToServerAsync(
"saveAs",
new Dictionary<string, object>
{
["path"] = path,
}).ConfigureAwait(false);
return;
}
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path)));
var stream = await _channel.SaveAsStreamAsync().ConfigureAwait(false);
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path)));
var stream = (await SendMessageToServerAsync("saveAsStream")
.ConfigureAwait(false)).GetObject<Stream>("stream", _connection);
await using (stream.ConfigureAwait(false))
{
using (var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
Expand All @@ -81,13 +91,15 @@ public async Task SaveAsAsync(string path)
[MethodImpl(MethodImplOptions.NoInlining)]
public async Task<System.IO.Stream> CreateReadStreamAsync()
{
var stream = await _channel.StreamAsync().ConfigureAwait(false);
var stream = (await SendMessageToServerAsync<JsonElement?>("stream")
.ConfigureAwait(false))?.GetObject<Stream>("stream", _connection);
return stream.StreamImpl;
}

internal Task CancelAsync() => _channel.CancelAsync();
internal Task CancelAsync() => SendMessageToServerAsync("cancel");

internal Task<string> FailureAsync() => _channel.FailureAsync();
internal async Task<string> FailureAsync() => (await SendMessageToServerAsync<JsonElement?>("failure")
.ConfigureAwait(false)).GetString("error", true);

internal Task DeleteAsync() => _channel.DeleteAsync();
internal Task DeleteAsync() => SendMessageToServerAsync("delete");
}
20 changes: 17 additions & 3 deletions src/Playwright/Core/BindingCall.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Playwright.Helpers;
using Microsoft.Playwright.Transport;
using Microsoft.Playwright.Transport.Channels;
using Microsoft.Playwright.Transport.Protocol;
Expand Down Expand Up @@ -96,15 +97,28 @@ internal async Task CallAsync(Delegate binding)
}
}

await _channel.ResolveAsync(ScriptsHelper.SerializedArgument(result)).ConfigureAwait(false);
await SendMessageToServerAsync("resolve", new Dictionary<string, object>
{
["result"] = ScriptsHelper.SerializedArgument(result),
}).ConfigureAwait(false);
}
catch (TargetInvocationException ex)
{
await _channel.RejectAsync(ex.InnerException).ConfigureAwait(false);
await SendMessageToServerAsync(
"reject",
new Dictionary<string, object>
{
["error"] = ex.InnerException.ToObject(),
}).ConfigureAwait(false);
}
catch (Exception ex)
{
await _channel.RejectAsync(ex).ConfigureAwait(false);
await SendMessageToServerAsync(
"reject",
new Dictionary<string, object>
{
["error"] = ex.ToObject(),
}).ConfigureAwait(false);
}
}
}
Loading

0 comments on commit ba2e378

Please sign in to comment.