Skip to content
Merged
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
2 changes: 2 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ Everything in PuppeteerSharp is inspired by the original Puppeteer library, but

When editing C# files, always place static members before non-static members (SA1204/SA1202 style rules). Never place a static method after instance methods.

StyleCop enforces a strict member ordering inside a class, applied in this priority: (1) member *kind* - fields, then constructors, then properties/indexers/events, then methods (SA1201: "a method should not follow a field/property/event"); (2) within each kind, *accessibility* - public, then internal, then protected internal, then protected, then private (SA1202); (3) within each accessibility group, *static before instance* (SA1204). When adding a new private helper method, it does not belong near the top of the class or next to the fields/properties it supports logically - it belongs in the private-methods section, after all public/internal/protected methods, grouped with other private statics before private instance methods.

## Git Workflow

Always verify which git branch you are on before making commits or creating PRs. Never commit to main/master. If the task requires a new branch, create it immediately and confirm with `git branch --show-current` before proceeding.
Expand Down
225 changes: 0 additions & 225 deletions lib/PuppeteerSharp/Bidi/BidiPage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -294,174 +294,6 @@ public override async Task<IResponse> ReloadAsync(ReloadOptions options)
return waitForNavigationTask.Result;
}

/// <inheritdoc />
public override async Task WaitForNetworkIdleAsync(WaitForNetworkIdleOptions options = null)
{
var timeout = options?.Timeout ?? DefaultTimeout;
var idleTime = options?.IdleTime ?? 500;
var concurrency = options?.Concurrency ?? 0;

var networkIdleTcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);

var idleTimer = new System.Timers.Timer { Interval = idleTime, AutoReset = false };

idleTimer.Elapsed += (_, _) => { networkIdleTcs.TrySetResult(true); };

var inflightRequests = 0;
var requestLock = new object();

void Evaluate()
{
idleTimer.Stop();

lock (requestLock)
{
if (inflightRequests <= concurrency)
{
idleTimer.Start();
}
}
}

void RequestEventListener(object sender, RequestEventArgs e)
{
lock (requestLock)
{
inflightRequests++;
}

Evaluate();
}

void RequestFinishedEventListener(object sender, RequestEventArgs e)
{
lock (requestLock)
{
inflightRequests = Math.Max(0, inflightRequests - 1);
}

Evaluate();
}

void ResponseEventListener(object sender, ResponseCreatedEventArgs e)
{
lock (requestLock)
{
inflightRequests = Math.Max(0, inflightRequests - 1);
}

Evaluate();
}

void Cleanup()
{
idleTimer.Stop();
idleTimer.Dispose();

Request -= RequestEventListener;
RequestFinished -= RequestFinishedEventListener;
RequestFailed -= RequestFinishedEventListener;
Response -= ResponseEventListener;
}

Request += RequestEventListener;
RequestFinished += RequestFinishedEventListener;
RequestFailed += RequestFinishedEventListener;
Response += ResponseEventListener;

Evaluate();

await Task.WhenAny(networkIdleTcs.Task, ClosedTask).WithTimeout(timeout, t =>
{
Cleanup();

return new TimeoutException($"Timeout of {t.TotalMilliseconds} ms exceeded");
}).ConfigureAwait(false);

Cleanup();

if (ClosedTask.IsFaulted)
{
await ClosedTask.ConfigureAwait(false);
}
}

/// <inheritdoc />
public override async Task<IRequest> WaitForRequestAsync(Func<IRequest, bool> predicate, WaitForOptions options = null)
{
var timeout = options?.Timeout ?? DefaultTimeout;
var requestTcs = new TaskCompletionSource<IRequest>(TaskCreationOptions.RunContinuationsAsynchronously);

void RequestEventListener(object sender, RequestEventArgs e)
{
if (predicate(e.Request))
{
requestTcs.TrySetResult(e.Request);
Request -= RequestEventListener;
}
}

Request += RequestEventListener;

try
{
await Task.WhenAny(requestTcs.Task, ClosedTask).WithTimeout(timeout, t =>
new TimeoutException($"Timeout of {t.TotalMilliseconds} ms exceeded")).ConfigureAwait(false);

if (ClosedTask.IsFaulted)
{
await ClosedTask.ConfigureAwait(false);
}

return await requestTcs.Task.ConfigureAwait(false);
}
finally
{
Request -= RequestEventListener;
}
}

/// <inheritdoc />
public override async Task<IResponse> WaitForResponseAsync(Func<IResponse, Task<bool>> predicate, WaitForOptions options = null)
{
var timeout = options?.Timeout ?? DefaultTimeout;
var responseTcs = new TaskCompletionSource<IResponse>(TaskCreationOptions.RunContinuationsAsynchronously);

async void ResponseHandler(object sender, ResponseCreatedEventArgs e)
{
try
{
if (await predicate(e.Response).ConfigureAwait(false))
{
responseTcs.TrySetResult(e.Response);
}
}
catch (Exception ex)
{
responseTcs.TrySetException(ex);
}
}

Response += ResponseHandler;

try
{
await Task.WhenAny(responseTcs.Task, ClosedTask).WithTimeout(timeout, t =>
new TimeoutException($"Timeout of {t.TotalMilliseconds} ms exceeded")).ConfigureAwait(false);

if (ClosedTask.IsFaulted)
{
await ClosedTask.ConfigureAwait(false);
}

return await responseTcs.Task.ConfigureAwait(false);
}
finally
{
Response -= ResponseHandler;
}
}

/// <inheritdoc />
public override async Task<FileChooser> WaitForFileChooserAsync(WaitForOptions options = null)
{
Expand Down Expand Up @@ -509,63 +341,6 @@ await Task.WhenAny(fileChooserTcs.Task, ClosedTask).WithTimeout(timeout, t =>
/// <inheritdoc />
public override Task SetBurstModeOffAsync() => throw new NotImplementedException();

/// <inheritdoc />
public override async Task<IFrame> WaitForFrameAsync(Func<IFrame, bool> predicate, WaitForOptions options = null)
{
if (predicate == null)
{
throw new ArgumentNullException(nameof(predicate));
}

var timeout = options?.Timeout ?? DefaultTimeout;
var frameTcs = new TaskCompletionSource<IFrame>(TaskCreationOptions.RunContinuationsAsynchronously);

void FrameNavigatedEventListener(object sender, FrameNavigatedEventArgs e)
{
if (predicate(e.Frame))
{
frameTcs.TrySetResult(e.Frame);
FrameNavigated -= FrameNavigatedEventListener;
}
}

void FrameAttachedEventListener(object sender, FrameEventArgs e)
{
if (predicate(e.Frame))
{
frameTcs.TrySetResult(e.Frame);
FrameAttached -= FrameAttachedEventListener;
}
}

FrameAttached += FrameAttachedEventListener;
FrameNavigated += FrameNavigatedEventListener;

var eventRace = Task.WhenAny(frameTcs.Task, ClosedTask).WithTimeout(timeout, t =>
{
FrameAttached -= FrameAttachedEventListener;
FrameNavigated -= FrameNavigatedEventListener;
return new TimeoutException($"Timeout of {t.TotalMilliseconds} ms exceeded");
});

foreach (var frame in Frames)
{
if (predicate(frame))
{
return frame;
}
}

await eventRace.ConfigureAwait(false);

if (ClosedTask.IsFaulted)
{
await ClosedTask.ConfigureAwait(false);
}

return await frameTcs.Task.ConfigureAwait(false);
}

/// <inheritdoc />
public override async Task SetGeolocationAsync(GeolocationOption options)
{
Expand Down
53 changes: 23 additions & 30 deletions lib/PuppeteerSharp/Browser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@
using PuppeteerSharp.Cdp;
using PuppeteerSharp.Helpers;
using PuppeteerSharp.QueryHandlers;
using ReactiveExtensionsSharp;
using ReactiveExtensionsSharp.Extras;
using ReactiveExtensionsSharp.Operators;
using RxSharp = ReactiveExtensionsSharp;

namespace PuppeteerSharp
{
Expand Down Expand Up @@ -148,42 +152,31 @@ public async Task<ITarget> WaitForTargetAsync(Func<ITarget, bool> predicate, Wai

var timeout = options?.Timeout ?? DefaultWaitForTimeout;
var cancellationToken = options?.CancellationToken ?? default;
var targetCompletionSource = new TaskCompletionSource<ITarget>(TaskCreationOptions.RunContinuationsAsynchronously);

void TargetHandler(object sender, TargetChangedArgs e)
{
if (predicate(e.Target))
{
targetCompletionSource.TrySetResult(e.Target);
}
}

CancellationTokenRegistration? cancellationRegistration = null;
using var created = RxExtensions.FromEventBuffered<TargetChangedArgs>(h => TargetCreated += h, h => TargetCreated -= h);
using var changed = RxExtensions.FromEventBuffered<TargetChangedArgs>(h => TargetChanged += h, h => TargetChanged -= h);

try
{
TargetCreated += TargetHandler;
TargetChanged += TargetHandler;

if (cancellationToken != default)
{
cancellationRegistration = cancellationToken.Register(
() => targetCompletionSource.TrySetCanceled(cancellationToken));
}

var existingTarget = Targets().FirstOrDefault(predicate);
if (existingTarget != null)
{
return existingTarget;
}

return await targetCompletionSource.Task.WithTimeout(timeout).ConfigureAwait(false);
// causeFactory: null (the default) so cancellation and timeout keep their own distinct
// exception types below - RaceWithSignalAndTimer would otherwise use one factory for both.
return await created.AsObservable()
.MergeWith(changed.AsObservable())
.Map(e => (ITarget)e.Target)
.MergeWith(Observable.From(Targets()))
.Filter(predicate)
.RaceWithSignalAndTimer(TimeSpan.FromMilliseconds(timeout), cancellationToken)
.ConfigureAwait(false);
}
catch (TimeoutException)
{
throw new TimeoutException($"Timeout of {timeout} ms exceeded");
}
finally
catch (OperationCanceledException)
{
cancellationRegistration?.Dispose();
TargetCreated -= TargetHandler;
TargetChanged -= TargetHandler;
// TaskCanceledException, not the plain OperationCanceledException the timeout/cancellation
// race defaults to: existing callers (and tests) rely on the exact pre-ReactiveExtensionsSharp cancellation type.
throw new TaskCanceledException();
}
}

Expand Down
Loading
Loading