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
6 changes: 3 additions & 3 deletions src/E2E/Engine/PageScript.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1199,9 +1199,9 @@ internal static class PageScript
}
""";

// Whether an element is a frame, the only element a frame locator can enter.
public const string IsFrameElement = """
(el) => el.tagName === "IFRAME" || el.tagName === "FRAME"
// Whether each element is a frame, the only element a frame locator can enter. An element gone since the count lists nothing.
public const string AreFrameElements = """
(els) => els.map((el) => el.tagName === "IFRAME" || el.tagName === "FRAME")
""";

// Where an iframe element's content box, the box its document's viewport
Expand Down
53 changes: 46 additions & 7 deletions src/E2E/Engine/WebEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1396,20 +1396,28 @@ private async Task<string> FrameAsync(IReadOnlyList<string> frames, OperationBud
var count = await budget.WithinAsync(element.CountAsync()).ConfigureAwait(false);
if (count == 0)
{
throw new EngineException(EngineErrorCodes.FrameNotFound, $"no frame matches {selector}", retryable: true);
throw NoFrame(selector);
}

if (count > 1)
{
throw new EngineException(EngineErrorCodes.FrameAmbiguous, $"{count} frames match {selector}", retryable: false);
}

refs.Add((await budget.WithinAsync(element.EvaluateAllAsync<string?[]>(PageScript.RefsOrForce, forcing.Mark)).ConfigureAwait(false))[0]);
// The iframe can go between the count and this read: it then lists nothing, as a count of zero says.
var listed = await budget.WithinAsync(element.EvaluateAllAsync<string?[]>(PageScript.RefsOrForce, forcing.Mark)).ConfigureAwait(false);
refs.Add(listed.Length > 0 ? listed[0] : throw NoFrame(selector));
scope = scope is null ? Page.FrameLocator(selector) : scope.FrameLocator(selector);
}

// A selector counts one element; only an iframe is a frame boundary.
if (!await budget.WithinAsync(element!.EvaluateAsync<bool>(PageScript.IsFrameElement, null, new LocatorEvaluateOptions { Timeout = budget.PlaywrightTimeout })).ConfigureAwait(false))
// A selector counts one element; only an iframe is a frame boundary. Read without waiting for the element: an iframe that went since the count is no frame, not an element to wait for.
var isFrame = await budget.WithinAsync(element!.EvaluateAllAsync<bool[]>(PageScript.AreFrameElements)).ConfigureAwait(false);
if (isFrame.Length == 0)
{
throw NoFrame(frames[^1]);
}

if (!isFrame[0])
{
throw new EngineException(EngineErrorCodes.FrameNotFound, $"{frames[^1]} matches an element that is not an iframe", retryable: true);
}
Expand All @@ -1429,6 +1437,8 @@ private async Task<string> FrameAsync(IReadOnlyList<string> frames, OperationBud
return refs[^1]!;
}

private static EngineException NoFrame(string selector) => new(EngineErrorCodes.FrameNotFound, $"no frame matches {selector}", retryable: true);

/// <summary>
/// The refs of the nodes the elements <paramref name="selector"/> names have, inside the frame the chain names or the page. An element
/// the observation does not list is marked in the page and counted in <paramref name="forcing"/>: the next observation lists it.
Expand Down Expand Up @@ -3619,17 +3629,22 @@ private async Task UploadFilesAsync(IElementHandle element, IReadOnlyList<string
IFileChooser chooser;
try
{
chooser = await opened.ConfigureAwait(false);
// On a loaded machine the deadline that wraps this upload can fire together with Playwright's timeout, which is the lead sooner.
// Upstream's earlier timer always wins that race; here that deadline gives the same answer.
chooser = await budget.AwaitingAsync(opened, () => NoFileChooser(null)).ConfigureAwait(false);
}
catch (System.TimeoutException ex)
{
throw new EngineException(EngineErrorCodes.NotActionable, "upload clicked the control but it opened no file chooser", retryable: false, ex);
throw NoFileChooser(ex);
}

budget.ThrowIfExpired();
await chooser.SetFilesAsync(paths, new FileChooserSetFilesOptions { Timeout = budget.PlaywrightTimeout }).ConfigureAwait(false);
}

private static EngineException NoFileChooser(Exception? cause) =>
new(EngineErrorCodes.NotActionable, "upload clicked the control but it opened no file chooser", retryable: false, cause);

/// <summary>How often a check or uncheck reads the control's state after the click.</summary>
private static readonly TimeSpan CheckPollInterval = TimeSpan.FromMilliseconds(100);

Expand Down Expand Up @@ -4162,6 +4177,7 @@ internal sealed class OperationBudget
private readonly string _label;
private readonly CancellationToken _cancellationToken;
private readonly TimeProvider _clock;
private volatile Func<EngineException>? _atDeadline;

// startedAt is when the operation began, on the clock, when engine work such as a reconnect already spent part of its budget.
public OperationBudget(TimeSpan timeout, string label, CancellationToken cancellationToken, TimeProvider? clock = null, long? startedAt = null)
Expand All @@ -4184,6 +4200,29 @@ public float PlaywrightTimeout
}
}

/// <summary>
/// Awaits a call whose own timeout is the lead ahead of the deadline. If the deadline passes first, because both fired in one stall
/// of a loaded machine, the deadline that wraps this call (<see cref="WithinAsync(Task)"/>) ends it as <paramref name="atDeadline"/>
/// answers, not as <c>OPERATION_TIMEOUT</c>. The answer stays when the call fails on its timeout, and goes on success or another
/// failure, so a later deadline is a plain timeout again.
/// </summary>
public async Task<T> AwaitingAsync<T>(Task<T> call, Func<EngineException> atDeadline)
{
_atDeadline = atDeadline;
try
{
var result = await call.ConfigureAwait(false);
_atDeadline = null;
return result;
}
catch (Exception ex) when (ex is not System.TimeoutException)
{
// Another failure ends the operation on its own answer; a deadline after it is a plain timeout.
_atDeadline = null;
throw;
}
}

/// <summary>Waits for <paramref name="call"/> until the deadline, then abandons it as <c>OPERATION_TIMEOUT</c>.</summary>
public async Task WithinAsync(Task call)
{
Expand Down Expand Up @@ -4243,7 +4282,7 @@ private TimeSpan Remaining()
return left > TimeSpan.Zero ? left : throw Timeout();
}

private EngineException Timeout() => new(EngineErrorCodes.OperationTimeout, _label + " timed out", retryable: false);
private EngineException Timeout() => _atDeadline?.Invoke() ?? new(EngineErrorCodes.OperationTimeout, _label + " timed out", retryable: false);
}

/// <summary>
Expand Down
24 changes: 22 additions & 2 deletions tests/E2E.Tests/Actions/DispatchLocatorActionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,21 @@ public async Task Reports_a_failed_click_without_leaving_the_chooser_wait_unhand
{
// A disabled button never becomes clickable, so the click fails while the chooser wait is still pending.
var unobserved = new List<string>();
void OnUnobserved(object? sender, UnobservedTaskExceptionEventArgs args) => unobserved.Add(args.Exception.ToString());
void OnUnobserved(object? sender, UnobservedTaskExceptionEventArgs args)
{
lock (unobserved)
{
unobserved.Add(args.Exception.ToString());
}
}

// The listener is process-wide: finalize what earlier tests left behind before it starts, so only this test's tasks reach it.
for (var round = 0; round < 2; round++)
{
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true);
GC.WaitForPendingFinalizers();
}

TaskScheduler.UnobservedTaskException += OnUnobserved;
try
{
Expand All @@ -182,7 +196,13 @@ await RunAsync(
TaskScheduler.UnobservedTaskException -= OnUnobserved;
}

Assert.DoesNotContain(unobserved, text => text.Contains("filechooser", StringComparison.OrdinalIgnoreCase));
List<string> leaked;
lock (unobserved)
{
leaked = unobserved.Where(text => text.Contains("filechooser", StringComparison.OrdinalIgnoreCase)).ToList();
}

Assert.True(leaked.Count == 0, "An unobserved task exception names the file chooser:\n" + string.Join("\n---\n", leaked));
}

private static async Task<SemanticNode> FindByNameAsync(IEngineSession session, string name)
Expand Down
Loading