Skip to main content

Responder

Struct Responder 

Source
pub struct Responder<T: JsonRpcResponse = Value, P: Protocol = Raw> { /* private fields */ }
Expand description

The context to respond to an incoming request.

This context is provided to request handlers and serves a dual role:

  1. Respond to the request - Use respond or respond_with_result to send the response
  2. Send other messages - Use the ConnectionTo parameter passed to your handler, which provides send_request, send_notification, and spawn

§Example

connection.on_receive_request(async |req: ProcessRequest, responder, cx| {
    // Send a notification while processing
    cx.send_notification(StatusUpdate {
        message: "processing".into(),
    })?;

    // Do some work...
    let result = process(&req.data)?;

    // Respond to the request
    responder.respond(ProcessResponse { result })
}, agent_client_protocol::on_receive_request!())

§Event Loop Considerations

Like all handlers, request handlers run on the event loop. Use spawn for expensive operations to avoid blocking the connection.

See the Event Loop and Concurrency section for more details.

§Drop behavior

A request must be answered. If a responder for a request is dropped without a response having been sent through it, the SDK answers the request itself with an error, so the peer is never left waiting:

No automatic response is sent when:

  • a response was already sent through the responder (any of the respond* methods), or the responder was handed to something that answers through it (such as SentRequest::forward_response_to) — only dropping the responder itself without responding triggers the fallback;
  • the responder was moved into another owner (another task, a wrapped responder from cast or wrap_params, a retried Dispatch); that owner’s eventual drop is what counts;
  • the connection is shutting down or has terminated.

When a handler drops the responder and then returns an error, that error is the response instead of the generic fallback.

The automatic error is an ordinary error response: for example, a dropped initialize responder fails initialization just as an explicit error would.

§Protocol version

P is the Protocol marker and selects the type id returns. Typed handlers on Client.v1(), Agent.v1() and Proxy.v1() receive V1 responders and those on the v2 builders receive V2 responders. The version-neutral raw dispatch layer (HandleDispatchFrom, MatchDispatch) uses the default, Raw. raw_id returns the wire ID whatever the marker; into_protocol and into_raw convert between markers.

Implementations§

Source§

impl<P: Protocol> Responder<Value, P>

Source

pub fn cast<T: JsonRpcResponse>(self) -> Responder<T, P>

Cast this request context to a different response type.

The provided type T will be serialized to JSON before sending.

Source§

impl<T: JsonRpcResponse, P: Protocol> Responder<T, P>

Source

pub fn method(&self) -> &str

Method of the incoming request

Source

pub fn id(&self) -> &P::RequestId

ID of the incoming request, as this responder’s protocol version types it.

On a V2 responder this is never null: the SDK rejects v2 requests with a null ID before dispatch.

Source

pub fn raw_id(&self) -> &RawJsonRpcId

ID of the incoming request exactly as it appeared on the wire.

This is the same ID as id, in the version-neutral form used by routers, forwarders and tracing.

Source

pub fn cancellation(&self) -> RequestCancellation

Returns the cancellation marker for this request.

The marker is set when the peer sends $/cancel_request for this request’s JSON-RPC ID. Cancellation is cooperative: handlers should use the marker to stop long-running work and then respond. Unless the method defines a successful response for cancellation (for example a permission request’s cancelled outcome), that response is Error::request_cancelled (-32800) rather than partial data. Dropping the responder of a cancelled request sends that error automatically.

Source

pub fn erase_to_json(self) -> Responder<Value, P>

Convert to a Responder that expects a JSON value and which checks (dynamically) that the JSON value it receives can be converted to T.

Source

pub fn wrap_method(self, method: String) -> Responder<T, P>

Return a new Responder with a different method name.

Source

pub fn wrap_params<U: JsonRpcResponse>( self, wrap_fn: impl FnOnce(&str, Result<U, Error>) -> Result<T, Error> + Send + 'static, ) -> Responder<U, P>

Return a new Responder that expects a response of type U.

wrap_fn will be invoked with the method name and the result to transform type U into type T before sending.

Source

pub fn respond_with_result( self, response: Result<T, Error>, ) -> Result<(), Error>

Respond to the JSON-RPC request with either a value (Ok) or an error (Err).

Source

pub fn respond(self, response: T) -> Result<(), Error>

Respond to the JSON-RPC request with a value.

Source

pub fn respond_with_internal_error( self, message: impl ToString, ) -> Result<(), Error>

Respond to the JSON-RPC request with an internal error containing a message.

Source

pub fn respond_with_error(self, error: Error) -> Result<(), Error>

Respond to the JSON-RPC request with an error.

Source

pub fn into_raw(self) -> Responder<T, Raw>

The same responder with a version-neutral Raw request ID, for code that is not tied to one protocol version, such as a HandleDispatchFrom implementation. This never fails.

Source§

impl<T: JsonRpcResponse> Responder<T, Raw>

Source

pub fn into_protocol<Q: Protocol>(self) -> Result<Responder<T, Q>, Error>

Convert this version-neutral responder to protocol Q’s responder, for example to pass a responder from a HandleDispatchFrom or MatchDispatch handler to a v2 session helper.

Only the request ID’s type changes. It fails only when Q does not allow the ID: protocol v2 rejects null with the Invalid Request error (-32600) that a v2 connection sends for a null request ID. That cannot happen for a request received on a v2 connection, which rejects such requests before dispatch. On failure the responder is dropped, which answers the request with an error.

let responder: agent_client_protocol::v1::Responder<schema::PromptResponse> =
    responder.into_protocol::<V1>()?;
let id: &schema::RequestId = responder.id();

Trait Implementations§

Source§

impl<T: JsonRpcResponse, P: Protocol> Debug for Responder<T, P>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<T = Value, P = Raw> !RefUnwindSafe for Responder<T, P>

§

impl<T = Value, P = Raw> !Sync for Responder<T, P>

§

impl<T = Value, P = Raw> !UnwindSafe for Responder<T, P>

§

impl<T, P> Freeze for Responder<T, P>
where HandleId<P>: Freeze, Box<dyn FnOnce(Result<T, Error>) -> Result<(), Error> + Send>: Freeze,

§

impl<T, P> Send for Responder<T, P>
where HandleId<P>: Send, Box<dyn FnOnce(Result<T, Error>) -> Result<(), Error> + Send>: Send,

§

impl<T, P> Unpin for Responder<T, P>
where HandleId<P>: Unpin, Box<dyn FnOnce(Result<T, Error>) -> Result<(), Error> + Send>: Unpin,

§

impl<T, P> UnsafeUnpin for Responder<T, P>
where HandleId<P>: UnsafeUnpin, Box<dyn FnOnce(Result<T, Error>) -> Result<(), Error> + Send>: UnsafeUnpin,

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> IntoMaybeUndefined<T> for T

Source§

fn into_maybe_undefined(self) -> MaybeUndefined<T>

Converts this value into a three-state builder argument.
Source§

impl<T> IntoOption<T> for T

Source§

fn into_option(self) -> Option<T>

Converts this value into an optional builder argument.
Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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