Skip to content

Conversation

RenderMichael
Copy link
Contributor

@RenderMichael RenderMichael commented Oct 11, 2025

User description

🔗 Related Issues

Fixes #15329

  • New feature (non-breaking change which adds functionality and tests!)

New API surface:

var permissions = bidi.AsPermissions();
await permissions.SetPermissionAsync("geolocation", PermissionState.Denied, newPage, userContext.UserContext);

PR Type

Enhancement


Description

  • Enable external BiDi module creation and extension

  • Refactor module architecture with InternalModule base class

  • Expose Broker and JsonOptions for external access

  • Simplify module creation with public static method


Diagram Walkthrough

flowchart LR
  BiDi["BiDi Class"] -- "exposes" --> Broker["Internal Broker"]
  BiDi -- "exposes" --> JsonOptions["JSON Options"]
  Module["Base Module"] -- "extends" --> InternalModule["InternalModule"]
  InternalModule -- "used by" --> AllModules["All Built-in Modules"]
  Module -- "public creation" --> ExternalModules["External Modules"]
Loading

File Walkthrough

Relevant files
Enhancement
13 files
BiDi.cs
Expose internal properties and refactor module creation   
+26/-21 
InternalModule.cs
Add new base class for internal modules                                   
+34/-0   
Module.cs
Refactor to support external module creation                         
+6/-7     
BrowserModule.cs
Change inheritance to InternalModule                                         
+1/-1     
BrowsingContextModule.cs
Change inheritance to InternalModule                                         
+1/-1     
EmulationModule.cs
Change inheritance to InternalModule                                         
+1/-1     
InputModule.cs
Change inheritance to InternalModule                                         
+1/-1     
LogModule.cs
Change inheritance to InternalModule                                         
+1/-1     
NetworkModule.cs
Change inheritance to InternalModule                                         
+1/-1     
ScriptModule.cs
Change inheritance to InternalModule                                         
+1/-1     
SessionModule.cs
Change inheritance to InternalModule                                         
+1/-1     
StorageModule.cs
Change inheritance to InternalModule                                         
+1/-1     
WebExtensionModule.cs
Change inheritance to InternalModule                                         
+1/-1     

@qodo-merge-pro
Copy link
Contributor

qodo-merge-pro bot commented Oct 11, 2025

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
Ticket Compliance
🟡
🎫 #15329
🟢 Enable a minimal, public mechanism in .NET to implement extendable third-party BiDi
modules without relying on internal members.
Expose necessary BiDi primitives (e.g., broker/transport and JSON serialization
options/context) for external modules to function.
Provide a straightforward way for consumers to create/use external BiDi modules (e.g., a
factory/extension pattern).
Maintain compatibility with existing built-in modules while refactoring to allow
extensibility.
Include example usage feasibility similar to creating a Permissions module as an external
extension.
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
No custom compliance provided

Follow the guide to enable custom compliance check.

  • Update
Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@qodo-merge-pro
Copy link
Contributor

qodo-merge-pro bot commented Oct 11, 2025

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Validate serializer context against options

In the Create method, validate that the provided cachedContext is compatible
with the jsonOptions by comparing their Options properties, and throw an
ArgumentException if they do not match.

dotnet/src/webdriver/BiDi/Module.cs [34-45]

 public static TModule Create<TModule>(BiDi bidi, JsonSerializerOptions jsonOptions, JsonSerializerContext? cachedContext = null)
     where TModule : Module, new()
 {
+    if (cachedContext is not null && cachedContext.Options != jsonOptions)
+    {
+        throw new ArgumentException("The provided JsonSerializerContext is not compatible with the provided JsonSerializerOptions.", nameof(cachedContext));
+    }
+
     TModule module = new()
     {
         Broker = bidi.Broker,
     };
 
     module.JsonContext = cachedContext ?? module.Initialize(jsonOptions);
 
     return module;
 }
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies a potential configuration issue in the public Create method and proposes a validation check to prevent runtime errors, which enhances the robustness of the API.

Low
Learned
best practice
Validate constructor input URL

Add argument validation to ensure url is not null/empty and is an absolute URI,
throwing ArgumentException/ArgumentNullException with clear messages.

dotnet/src/webdriver/BiDi/BiDi.cs [64-83]

 private BiDi(string url)
 {
-    var uri = new Uri(url);
+    if (url is null) throw new ArgumentNullException(nameof(url));
+    if (string.IsNullOrWhiteSpace(url)) throw new ArgumentException("URL must not be empty.", nameof(url));
+    if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
+        throw new ArgumentException("URL must be a valid absolute URI.", nameof(url));
 
     JsonOptions = DefaultBiDiOptions();
 
     _jsonContext = new BiDiJsonSerializerContext(JsonOptions);
 
     Broker = new Broker(this, uri, JsonOptions);
     SessionModule = Module.Create<Session.SessionModule>(this, JsonOptions, _jsonContext);
     BrowsingContext = Module.Create<BrowsingContext.BrowsingContextModule>(this, JsonOptions, _jsonContext);
     Browser = Module.Create<Browser.BrowserModule>(this, JsonOptions, _jsonContext);
     Network = Module.Create<Network.NetworkModule>(this, JsonOptions, _jsonContext);
     InputModule = Module.Create<Input.InputModule>(this, JsonOptions, _jsonContext);
     Script = Module.Create<Script.ScriptModule>(this, JsonOptions, _jsonContext);
     Log = Module.Create<Log.LogModule>(this, JsonOptions, _jsonContext);
     Storage = Module.Create<Storage.StorageModule>(this, JsonOptions, _jsonContext);
     WebExtension = Module.Create<WebExtension.WebExtensionModule>(this, JsonOptions, _jsonContext);
     Emulation = Module.Create<Emulation.EmulationModule>(this, JsonOptions, _jsonContext);
 }
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why:
Relevant best practice - Validate inputs early with precise checks to prevent null/invalid argument issues.

Low
  • Update

protected Broker Broker { get; private set; }

internal BiDiJsonSerializerContext JsonContext { get; private set; }
internal JsonSerializerContext JsonContext { get; private set; }
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not ready to generalize it in this PR. Still not clear how to move on.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have an example in this PR’s description, of how to move forward with these changes.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I though making Module.Create(...) to public would be enough, please give me time to review.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Observed it is theoretical changes. Let be practicable.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is, except for the shared JSON context introduced in #16402

It is not theoretical changes.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I came to the following:

  1. BiDi has new method AsModule<T>()
  2. PermissionsModule creates its own context based on options (and keep it as private field)

Then changes looks simple.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel introducing new AsModule<T>() method will be good for us:

  • we may introduce cached modules
  • it negotiates use of internal properties

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All right, AsModule<T> is required. Built-in modules are cached, third-party modules also want to be cached per bidi instance. Let's do it (here or in separate PR).

Copy link
Member

@nvborisenko nvborisenko left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No value,. In any case thank you.

@RenderMichael RenderMichael changed the title [dotnet] Enable external bidi modules [dotnet] Implement third-party Permissions module Oct 11, 2025

public sealed class BrowserModule : Module
{
internal new BiDiJsonSerializerContext JsonContext => (BiDiJsonSerializerContext)base.JsonContext;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@RenderMichael this piece is strange, seems there is no reason to keep JsonContext in base class. If you have the same opinion, I can remake it to private field.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The base class is responsible for creating the JSON context. This is the only way to bridge the gap between "strongly-typed JSON context" and the logic in Module.Create

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another way to get around this is by making the Json Context a generic parameter, eg. BrowserModule : Module<BiDiJsonSerializerContext>. That requires making BiDiJsonSerializerContext public, and more publicly exposed. I don't think that's desirable.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I also was thinking about BrowserModule : Module<BiDiJsonSerializerContext>, but it seems even stranger. Module of JsonContext... I am reading it hard, given that BiDiJsonSerializerContext cannot be inherited.

Ideally we should get rid of BiDiJsonSerializerContext, we are moving in this direction.

About internal new BiDiJsonSerializerContext JsonContext => (BiDiJsonSerializerContext)base.JsonContext;: For me it is risky, at least not obvious...

  • is it one time initialization? (question from interview)
  • what is executed first? our void Initialize(...) or this implicit initialization
  • does it mean that we cast each time when we invoke JsonContext getter?

Private field looks really simple.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we want to go that route, then we will have to undo optimizations such as this one: #16397

Otherwise, we will need a separate JSON context for each module

Ideally we should get rid of BiDiJsonSerializerContext, we are moving in this direction.

What do you have in mind?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Second optimization that would need to be de-optimized: #16392

Copy link
Member

@nvborisenko nvborisenko Oct 21, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Internal modules will still use global JsonContext for a while, because of f**g cross-referencing (stateful converters, polymorphic dto). In future, each module wants to:

void Initialize(BiDi bidi, JsonOptions options) // just common options like Naming policy
{
  var moduleOptions = new JsonOptions(options) // make a copy
  {
     Converters = { new MySpecificConverter(bidi) } // bad example, just to highlight possibilities
  }

  _myContext = new MyCoontext(moduleOptions);
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since we do cannot have a global JsonContext for third-party extensions, it looks like we will need 2 different kinds of modules: extensions and non-extension (core?).

because of f**g cross-referencing (stateful converters, polymorphic dto)

That shouldn't be a problem! We can get rid of stateful converters (very slightly less pleasant usability, I think it is no problem) and polymorphic DTOs got addressed by moving the converters out to attributes.

The only remaining converter is DateTimeOffsetConverter. We could go through to each instance of DateTimeOffset and add that converter as an attribute. Alternatively, we could change the type to long in the DTO, since it is technically magic. If we want to address that, then we will have no converters left!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DateTimeOffsetConverter is not a problem, it is kind of common JsonOptions. it is OK to have global well-known converters.

I don't want to block this PR, we can improve later. But seems private MyJsonContext should be here. Broker requires JsonTypeInfo.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since we do cannot have a global JsonContext for third-party extensions, it looks like we will need 2 different kinds of modules: extensions and non-extension (core?).

Each module should have own JsonContext, ideally. And it is out of scope of this PR.

internal JsonSerializerContext JsonContext { get; private set; }

protected virtual void Initialize(JsonSerializerOptions options) { }
protected abstract JsonSerializerContext Initialize(JsonSerializerOptions options);
Copy link
Member

@nvborisenko nvborisenko Oct 19, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should choose between void Initialize(...) and JsonSerializerContext ConfigureJsonContext(...). I vote for void, letting each module to decide whatever it wants. Input parameters might be changed in future (breaking change), but I think it will be another story.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't see an issue with this, especially because we have specific requirements

  1. Each Module controls its own JSON context
  2. Modules must be able to re-use contexts from a cache

Maybe we can rename this to CreateJsonContext, and if necessary, introduce a separate Initialize in the future?

return bidi;
}

public static PermissionsModule AsPermissions(this BiDi bidi)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is definitely should be in another class. The reason is we are CLS compatible (I don't still understand why, but anyway), meaning some languages cannot deal with extension methods. They will use static method: WebDriverExtensions.AsPermissions(bidi). But it is not extension of WebDriver.

We should introduce good name for static class, and its namespace.

BiDiExtensions.AsPermissions(bidi)?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When Bluetooth module comes to under umbrella, then what? Should we have single static class for all them, or they define own static class in theirs namespace?

I vote for "everything in their namespace". It would be good pattern to demonstrate good practices how to develop module. Separate namespace is not a problem, IDE is still able to suggest extension method.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

extension methods do not affect CLS compliance. Users can call WebDriverExtensions.AsPermissions(bidi) even on extension methods.

But I agree that extensions should be in separate files. I will make those changes.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My concern is about naming: WebDriverExtensions.AsPermissions(bidi) - it is not extension for WebDriver, it is for BiDi.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I followed the two suggestions: WebDriverExtensions -> BiDiExtensions, and permissions in its own area

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[🚀 Feature]: [dotnet] Provide a possibility to implement BiDi Permissions module

3 participants