Connection

Struct Connection 

Source
pub struct Connection<W, R>
where W: AsyncWrite + Unpin + Send + Sync + 'static, R: AsyncRead + Unpin + Send + Sync + 'static,
{ /* private fields */ }
Expand description

JSON-RPC connection to Playwright server

Manages request/response correlation and event dispatch. Uses sequential request IDs and oneshot channels for correlation.

§Thread Safety

Connection is thread-safe and can be shared across async tasks using Arc. Multiple concurrent requests are supported.

§Architecture

This follows the pattern from official Playwright bindings:

  • Python: Direct callback on message receive
  • Java: Callback map with synchronized access
  • .NET: ConcurrentDictionary with TaskCompletionSource

Rust implementation uses:

  • AtomicU32 for thread-safe ID generation
  • Arc<Mutex<HashMap>> for callback storage
  • tokio::sync::oneshot for request/response correlation

Implementations§

Source§

impl<W, R> Connection<W, R>
where W: AsyncWrite + Unpin + Send + Sync + 'static, R: AsyncRead + Unpin + Send + Sync + 'static,

Source

pub fn new( transport: PipeTransport<W, R>, message_rx: UnboundedReceiver<Value>, ) -> Self

Create a new Connection with the given transport

§Arguments
  • transport - Transport connected to Playwright server
  • message_rx - Receiver for incoming messages from transport
§Example
let (stdin_read, stdin_write) = duplex(1024);
let (stdout_read, stdout_write) = duplex(1024);

let (transport, message_rx) = PipeTransport::new(stdin_write, stdout_read);
let connection = Connection::new(transport, message_rx);
Source

pub async fn send_message( &self, guid: &str, method: &str, params: Value, ) -> Result<Value>

Send a message to the Playwright server and await response

This method:

  1. Generates a unique request ID
  2. Creates a oneshot channel for the response
  3. Stores the channel sender in the callbacks map
  4. Serializes and sends the request via transport
  5. Awaits the response on the receiver
§Arguments
  • guid - GUID of the target object (e.g., “page@abc123”)
  • method - Method name to invoke (e.g., “goto”)
  • params - Method parameters as JSON value
§Returns

The result value from the server, or an error if:

  • Transport send fails
  • Server returns an error
  • Connection is closed before response arrives

See module-level documentation for usage examples.

Source

pub async fn initialize_playwright( self: &Arc<Self>, ) -> Result<Arc<dyn ChannelOwner>>

Initialize the Playwright connection and return the root Playwright object

This method implements the initialization handshake with the Playwright server:

  1. Creates a temporary Root object
  2. Sends “initialize” message with sdkLanguage=“rust”
  3. Server creates BrowserType objects (sends __create__ messages)
  4. Server responds with Playwright GUID
  5. Looks up Playwright object from registry (guaranteed to exist)

The initialize message is synchronous - by the time the response arrives, all protocol objects have been created and registered.

§Returns

An Arc<dyn ChannelOwner> that is the Playwright object. Callers should downcast to Playwright type.

§Errors

Returns error if:

  • Initialize message fails to send
  • Server returns protocol error
  • Response is missing Playwright GUID
  • Playwright object not found in registry
  • Timeout after 30 seconds

See module-level documentation for usage examples.

See also:

Source

pub async fn run(self: &Arc<Self>)

Run the message dispatch loop

This method continuously reads messages from the transport and dispatches them:

  • Responses (with id) are correlated with pending requests
  • Events (without id) are dispatched to protocol objects (TODO: Future phase - event handling)

The loop runs until the transport channel is closed.

§Usage

This method should be spawned in a background task:

let conn = Arc::clone(&connection);
tokio::spawn(async move {
    conn.run().await;
});

Trait Implementations§

Source§

impl<W, R> ConnectionLike for Connection<W, R>
where W: AsyncWrite + Unpin + Send + Sync + 'static, R: AsyncRead + Unpin + Send + Sync + 'static,

Source§

fn send_message( &self, guid: &str, method: &str, params: Value, ) -> Pin<Box<dyn Future<Output = Result<Value>> + Send + '_>>

Send a message to the Playwright server and await response
Source§

fn register_object( &self, guid: Arc<str>, object: Arc<dyn ChannelOwner>, ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>>

Register an object in the connection’s registry
Source§

fn unregister_object( &self, guid: &str, ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>>

Unregister an object from the connection’s registry
Source§

fn get_object( &self, guid: &str, ) -> Pin<Box<dyn Future<Output = Result<Arc<dyn ChannelOwner>>> + Send + '_>>

Get an object by GUID

Auto Trait Implementations§

§

impl<W, R> !Freeze for Connection<W, R>

§

impl<W, R> !RefUnwindSafe for Connection<W, R>

§

impl<W, R> Send for Connection<W, R>

§

impl<W, R> Sync for Connection<W, R>

§

impl<W, R> Unpin for Connection<W, R>

§

impl<W, R> !UnwindSafe for Connection<W, R>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more