rig_core/wire.rs
1//! Operations, provider wires and their decoders. An [`Operation`] names what
2//! goes in, what comes out event by event and what ends a reply, and its
3//! [`Fold`] turns one reply's events and end into the response. A [`Wire`]
4//! describes a provider endpoint as plain data, encodes requests without
5//! transport access, and names a fresh [`Decoder`] for each reply. A decoder
6//! is told nothing about how the reply arrives, so buffered and streamed
7//! replies go through the same decoder and fold.
8//!
9//! ```
10//! use rig_core::wire::WireFrame;
11//!
12//! let frame = WireFrame::Bytes(b"response".to_vec());
13//! assert_eq!(frame.as_str(), "response");
14//! ```
15
16use crate::error::{EncodeError, ProviderError};
17use crate::http_client::MultipartForm;
18use crate::wasm_compat::{WasmCompatSend, WasmCompatSync};
19
20pub use crate::http_client::framing::{Framing, WireFrame};
21pub use crate::observe::{
22 AdapterErrorEnvelope, AdapterEvent, AdapterUsage, AdapterVerdict, ObservationSink,
23};
24
25pub(crate) mod secret;
26
27pub use secret::Secret;
28
29/// The request a wire sends, and how its reply is framed.
30///
31/// Data only: built by [`Wire::encode`] from the wire and the request, and
32/// read by the driver. A wire never touches a socket or a request extension.
33///
34/// `Debug` shows request methods and URI paths, not schemes, authorities,
35/// queries, header values or bodies. Paths are not scrubbed: callers must
36/// still avoid placing sensitive data in them.
37pub struct Encoded {
38 /// The HTTP request.
39 pub request: http::Request<Body>,
40 /// How the reply's bytes split into frames.
41 pub framing: Framing,
42 /// The reply header carrying the provider's transport request id
43 /// (Anthropic `request-id`, OpenAI `x-request-id`), when the provider
44 /// reports one. `None` is "does not report one", never an error.
45 pub request_id_header: Option<&'static str>,
46 /// Whether a streamed reply may omit `Content-Type` (one gateway
47 /// replays Responses bodies without it). A *wrong* content type is
48 /// still rejected.
49 pub relaxed_content_type: bool,
50 /// Stable endpoint template for observation grouping, without base-URL
51 /// prefixes or interpolated values. `None` uses the concrete request path.
52 pub route: Option<&'static str>,
53 /// Reads observation facts off each raw reply payload before
54 /// normalization discards them. `None` projects nothing.
55 pub project: Option<Projector>,
56 /// Whether a frame carries only analysis metadata: it still decodes, but
57 /// does not advance observation's EOF and corruption positions.
58 pub analysis_only: Option<fn(&WireFrame) -> bool>,
59}
60
61/// Reads one raw payload's observation facts (verdicts, usage, ids, error
62/// envelopes) through the sink. Text it forwards goes through
63/// [`ObservationSink::scrub`]: a payload can echo credentials.
64pub type Projector = fn(&[u8], &mut ObservationSink<'_>);
65
66impl Encoded {
67 /// One request whose provider reports no transport request id.
68 pub fn new(request: http::Request<Body>, framing: Framing) -> Self {
69 Self {
70 request,
71 framing,
72 request_id_header: None,
73 relaxed_content_type: false,
74 route: None,
75 project: None,
76 analysis_only: None,
77 }
78 }
79
80 /// Name the reply header carrying the provider's transport request id.
81 pub fn with_request_id_header(mut self, header: Option<&'static str>) -> Self {
82 self.request_id_header = header;
83 self
84 }
85
86 /// Accept a streamed reply that names no content type.
87 pub fn with_relaxed_content_type(mut self) -> Self {
88 self.relaxed_content_type = true;
89 self
90 }
91
92 /// Name the endpoint template observation groups attempts under.
93 pub fn with_route(mut self, route: Option<&'static str>) -> Self {
94 self.route = route;
95 self
96 }
97
98 /// Read observation facts off each reply payload through `project`.
99 pub fn with_projection(mut self, project: Projector) -> Self {
100 self.project = Some(project);
101 self
102 }
103
104 /// Exempt frames `analysis_only` accepts from observation's frame
105 /// positions.
106 pub fn with_analysis_only(mut self, analysis_only: fn(&WireFrame) -> bool) -> Self {
107 self.analysis_only = Some(analysis_only);
108 self
109 }
110}
111
112/// A request body: bytes, or a multipart form for the upload endpoints.
113///
114/// `Debug` prints the body's shape and size, never its bytes: a request
115/// body carries prompts, documents and uploaded files.
116pub enum Body {
117 /// A serialized body (JSON for every wire in this crate, or empty).
118 Bytes(Vec<u8>),
119 /// A multipart form (audio transcription, image edits).
120 Multipart(MultipartForm),
121}
122
123impl Body {
124 /// An empty body, for a `GET`.
125 pub fn empty() -> Self {
126 Self::Bytes(Vec::new())
127 }
128}
129
130impl std::fmt::Debug for Body {
131 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
132 match self {
133 Self::Bytes(bytes) => write!(f, "Bytes({} bytes)", bytes.len()),
134 Self::Multipart(_) => f.write_str("Multipart"),
135 }
136 }
137}
138
139impl std::fmt::Debug for Encoded {
140 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
141 // Diagnostics omit query, authority, headers and bodies. A caller's
142 // path can still contain sensitive data; it is not scrubbed here.
143 f.debug_struct("Encoded")
144 .field(
145 "request",
146 &(self.request.method(), self.request.uri().path()),
147 )
148 .field("framing", &self.framing)
149 .field("request_id_header", &self.request_id_header)
150 .field("relaxed_content_type", &self.relaxed_content_type)
151 .field("route", &self.route)
152 .field("project", &self.project.is_some())
153 .finish()
154 }
155}
156
157/// Reply mode used by the wire to select request encoding and framing.
158#[derive(Debug, Clone, Copy, PartialEq, Eq)]
159pub enum Mode {
160 /// One whole reply ([`Model::call`](crate::driver::Model::call)).
161 Unary,
162 /// A streamed reply ([`Model::stream`](crate::driver::Model::stream)).
163 Streaming,
164}
165
166/// An operation: what goes in, what comes out event by event, what ends a
167/// reply, and how those fold into one response.
168///
169/// Implemented once per operation, never per provider, so every provider of
170/// an operation is interchangeable behind a [`DynModel`](crate::DynModel).
171pub trait Operation: Sized + 'static {
172 /// The normalized request this operation accepts.
173 type Request: WasmCompatSend + 'static;
174 /// One decoded step of a reply.
175 type Event: WasmCompatSend + 'static;
176 /// What the provider sends when it ends the reply. A fold needs one to
177 /// produce a response, so a reply that stopped early has none.
178 type End: WasmCompatSend + 'static;
179 /// The normalized response the events and the end fold into.
180 type Response: WasmCompatSend + 'static;
181 /// One reply's state: it absorbs the events the consumer sees, then
182 /// folds them with the end into the response.
183 type Fold: Fold<Self> + WasmCompatSend + 'static;
184 /// Who builds the events: [`Free`] for events a decoder writes itself,
185 /// [`Assembled`] for the completion events only the writer's part
186 /// handles build.
187 type Emit: Emit<Self>;
188
189 /// The state for one reply to `request`, before its first frame. The
190 /// call says who answers and in which mode; an operation that records
191 /// telemetry opens its span here and hands it to
192 /// [`Call::instrument`].
193 fn fold(request: &Self::Request, call: &mut Call<'_>) -> Self::Fold;
194
195 /// Reject a request no provider of this operation can answer. The
196 /// driver calls it before the request is encoded, so a rejected request
197 /// reaches no wire or transport. Accepts every request by default.
198 fn validate(_request: &Self::Request) -> Result<(), ProviderError> {
199 Ok(())
200 }
201}
202
203/// Events a decoder builds and writes with [`Out::event`].
204#[derive(Debug, Clone, Copy, PartialEq, Eq)]
205pub enum Free {}
206
207/// Events only the completion writer's part handles build.
208#[derive(Debug, Clone, Copy, PartialEq, Eq)]
209pub enum Assembled {}
210
211/// Who builds an operation's events: [`Free`] or [`Assembled`]. Sealed.
212pub trait Emit<Op: Operation>: reply::Closing<Op> {}
213
214impl<Op: Operation> reply::Closing<Op> for Free {
215 fn close(_shared: &mut Shared<Op>) {}
216}
217
218impl<Op: Operation> Emit<Op> for Free {}
219
220/// What the driver knows about a call before its first frame.
221pub struct Call<'a> {
222 /// What the wire says about itself.
223 pub wire: &'a Descriptor<'a>,
224 /// How the reply arrives.
225 pub mode: Mode,
226 pub(crate) span: tracing::Span,
227}
228
229impl<'a> Call<'a> {
230 /// A call to the wire `wire` describes, in `mode`, under no span.
231 pub(crate) fn new(wire: &'a Descriptor<'a>, mode: Mode) -> Self {
232 Self {
233 wire,
234 mode,
235 span: tracing::Span::none(),
236 }
237 }
238
239 /// Run the call under `span`: a unary call sends under it and a stream
240 /// decodes under it.
241 pub fn instrument(&mut self, span: tracing::Span) {
242 self.span = span;
243 }
244}
245
246/// One reply's state for an operation.
247///
248/// Each event is [`absorb`](Self::absorb)ed as the consumer takes it, so
249/// the fold never runs ahead of what was delivered. The reply's end is what
250/// [`finish`](Self::finish) needs: without the provider's end there is no
251/// response.
252pub trait Fold<Op: Operation> {
253 /// Absorb one event the consumer is about to see. An error fails the
254 /// reply.
255 fn absorb(&mut self, event: &Op::Event) -> Result<(), ProviderError>;
256
257 /// The response, from the events absorbed, the provider's end and what
258 /// the driver learned about the reply.
259 fn finish(self, end: Op::End, reply: Reply) -> Result<Op::Response, ProviderError>;
260}
261
262/// What the driver learned about a reply beyond its events.
263#[derive(Debug, Clone, PartialEq)]
264pub struct Reply {
265 /// The provider descriptor name, for the response's `provider` field.
266 pub provider: String,
267 /// The reply's provider document (a completion's `raw`): the whole body
268 /// when it is one JSON document, else what the decoder recorded, else
269 /// `Null`.
270 pub raw: serde_json::Value,
271 /// The provider's transport request id from the reply headers.
272 pub provider_request_id: Option<String>,
273}
274
275/// Whether a decoder step left the reply open. Only [`Out::end`] makes an
276/// [`Ended`].
277#[derive(Debug)]
278#[must_use]
279pub enum Flow {
280 /// The reply continues.
281 More,
282 /// The provider ended the reply; nothing is read after it.
283 Ended(Ended),
284}
285
286/// Proof that a decoder ended its reply with [`Out::end`].
287#[derive(Debug)]
288pub struct Ended(());
289
290pub(crate) use reply::Shared;
291
292pub(crate) mod reply {
293 use std::collections::VecDeque;
294
295 use super::{Operation, ProviderError};
296 use crate::streaming::Item;
297
298 /// One reply's items and end, shared by the driver that writes them and
299 /// the stream that takes them.
300 pub struct Shared<Op: Operation> {
301 pub(crate) fold: Op::Fold,
302 pub(crate) items: VecDeque<Result<Item<Op::Event>, ProviderError>>,
303 pub(crate) end: Option<Op::End>,
304 pub(crate) raw: Option<serde_json::Value>,
305 /// The response a relayed reply's origin already folded.
306 pub(crate) response: Option<Op::Response>,
307 /// What the transport reported: the reply's request id, its whole
308 /// document and its request path.
309 pub(crate) request_id: Option<String>,
310 pub(crate) document: Option<serde_json::Value>,
311 pub(crate) route: String,
312 }
313
314 impl<Op: Operation> Shared<Op> {
315 pub(crate) fn new(fold: Op::Fold) -> Self {
316 Self {
317 fold,
318 items: VecDeque::new(),
319 end: None,
320 raw: None,
321 response: None,
322 request_id: None,
323 document: None,
324 route: String::new(),
325 }
326 }
327 }
328
329 /// What the reply's end closes before it is recorded.
330 pub trait Closing<Op: Operation> {
331 fn close(shared: &mut Shared<Op>);
332 }
333}
334
335/// What a runtime accounts for about a model. Each field matters to the
336/// operations that name it and is left at its default by the others.
337#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
338pub struct Capabilities {
339 /// What a completion provider composes.
340 pub completion: crate::completion::ProviderCapabilities,
341 /// The most documents one embedding or reranking request takes.
342 pub max_documents: usize,
343 /// The dimensionality of the returned vectors. Zero is unknown.
344 pub ndims: usize,
345 /// The embedding width the caller asked for, when they named one. `None`
346 /// and zero disable the check that replies honour it.
347 pub declared: Option<usize>,
348}
349
350impl Capabilities {
351 /// A completion provider's capabilities.
352 pub const fn completion(completion: crate::completion::ProviderCapabilities) -> Self {
353 Self {
354 completion,
355 ..Self::embedding(0, 0)
356 }
357 }
358
359 /// An embedding model's batch limit and width, with no width declared.
360 pub const fn embedding(max_documents: usize, ndims: usize) -> Self {
361 Self {
362 completion: crate::completion::ProviderCapabilities::new(),
363 max_documents,
364 ndims,
365 declared: None,
366 }
367 }
368
369 /// A reranking model's batch limit.
370 pub const fn rerank(max_documents: usize) -> Self {
371 Self::embedding(max_documents, 0)
372 }
373
374 /// Record the width the caller named, when they named one.
375 pub const fn declaring(mut self, declared: Option<usize>) -> Self {
376 self.declared = declared;
377 self
378 }
379
380 /// Returns [`ProviderError::MismatchedDimensions`] for the first width
381 /// differing from a positive caller declaration. Otherwise succeeds.
382 pub(crate) fn honour_declaration(
383 &self,
384 provider: &str,
385 widths: impl IntoIterator<Item = usize>,
386 ) -> Result<(), ProviderError> {
387 // Zero is rig's sentinel for an unknown width, never a claim about
388 // one: a model absent from every table this build knows resolves to
389 // it, and treating that as a declaration would fail every reply.
390 let Some(requested) = self.declared.filter(|declared| *declared > 0) else {
391 return Ok(());
392 };
393 let Some(returned) = widths.into_iter().find(|width| *width != requested) else {
394 return Ok(());
395 };
396 Err(ProviderError::MismatchedDimensions {
397 provider: provider.to_owned(),
398 requested,
399 returned,
400 })
401 }
402}
403
404/// What a wire says about itself: plain data, read before every call.
405#[derive(Debug, Clone)]
406pub struct Descriptor<'a> {
407 /// The provider descriptor name (`"anthropic"`), as records and
408 /// telemetry name it.
409 pub name: &'a str,
410 /// The model id the wire addresses, for telemetry. `None` for
411 /// operations that address no model.
412 pub model: Option<&'a str>,
413 /// What a runtime accounts for.
414 pub capabilities: Capabilities,
415 /// The telemetry operation for a call in each mode, when the endpoint
416 /// has a canonical name of its own (Gemini `generate_content`).
417 pub telemetry: Option<fn(Mode) -> crate::telemetry::GenAiOperation>,
418}
419
420impl<'a> Descriptor<'a> {
421 /// A wire named `name`, addressing no model, with default capabilities.
422 pub fn new(name: &'a str) -> Self {
423 Self {
424 name,
425 model: None,
426 capabilities: Capabilities::default(),
427 telemetry: None,
428 }
429 }
430
431 /// The model id the wire addresses, when it addresses one.
432 pub fn model(mut self, model: impl Into<Option<&'a str>>) -> Self {
433 self.model = model.into();
434 self
435 }
436
437 /// What a runtime accounts for.
438 pub fn capabilities(mut self, capabilities: Capabilities) -> Self {
439 self.capabilities = capabilities;
440 self
441 }
442
443 /// The endpoint's own telemetry operation for each mode.
444 pub fn telemetry(mut self, telemetry: fn(Mode) -> crate::telemetry::GenAiOperation) -> Self {
445 self.telemetry = Some(telemetry);
446 self
447 }
448}
449
450/// One classified wire frame.
451#[derive(Debug)]
452pub enum WireEvent<T> {
453 /// The frame carries a discriminator this client models and its payload
454 /// decoded fully.
455 Known(T),
456 /// Valid JSON not recognized by this classifier.
457 /// Drivers log structural metadata only and skip interpretation.
458 Unknown {
459 /// The unmodeled discriminator value.
460 event_type: String,
461 /// Full payload for raw passthrough, never warning logs. Debug is redacted.
462 value: crate::streaming::UnknownPayload,
463 },
464 /// Invalid JSON or a recognized frame that failed typed decoding.
465 /// Must not be demoted to `Unknown`.
466 Corrupt(serde_json::Error),
467}
468
469impl<T> WireEvent<T> {
470 /// An event a typed transport (an SDK event stream, a gRPC stream)
471 /// reported that this client does not model. The detail is kept for
472 /// raw passthrough, never for warning logs.
473 pub fn unrecognized(event_type: impl Into<String>, detail: impl Into<String>) -> Self {
474 Self::Unknown {
475 event_type: event_type.into(),
476 value: serde_json::Value::String(detail.into()).into(),
477 }
478 }
479
480 /// A modeled event a typed transport failed to decode.
481 pub fn malformed(message: impl std::fmt::Display) -> Self {
482 Self::Corrupt(<serde_json::Error as serde::de::Error>::custom(message))
483 }
484
485 /// Map the `Known` payload, preserving the classification.
486 ///
487 /// This is how an adapter layers a pure event-shape mapping on top of a
488 /// classifier without restating the triage: `Unknown` and `Corrupt` pass
489 /// through untouched, so policy stays with the driver.
490 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> WireEvent<U> {
491 match self {
492 Self::Known(event) => WireEvent::Known(f(event)),
493 Self::Unknown { event_type, value } => WireEvent::Unknown { event_type, value },
494 Self::Corrupt(error) => WireEvent::Corrupt(error),
495 }
496 }
497}
498
499/// Where a decoder writes one reply. The `'id` brand ties it, and every
500/// part handle it hands out, to that one reply: a handle cannot be used
501/// with another reply's writer or kept past its own.
502///
503/// ```compile_fail
504/// use rig_core::operation::Completion;
505/// use rig_core::wire::Out;
506///
507/// // A text part opened on one reply cannot grow on another.
508/// fn cross<'a, 'b>(a: &mut Out<'a, Completion>, b: &mut Out<'b, Completion>) {
509/// let part = a.text();
510/// b.push_text(&part, "x");
511/// }
512/// ```
513///
514/// ```compile_fail
515/// use rig_core::operation::{Completion, TextPart};
516/// use rig_core::wire::Out;
517///
518/// // A handle cannot outlive its reply to be used on a later one.
519/// struct Stash(Option<TextPart<'static>>);
520///
521/// fn keep<'id>(stash: &mut Stash, out: &mut Out<'id, Completion>) {
522/// stash.0 = Some(out.text());
523/// }
524/// ```
525pub struct Out<'id, Op: Operation> {
526 shared: &'id std::sync::Mutex<Shared<Op>>,
527 brand: std::marker::PhantomData<fn(&'id ()) -> &'id ()>,
528}
529
530impl<'id, Op: Operation> Out<'id, Op> {
531 pub(crate) fn new(shared: &'id std::sync::Mutex<Shared<Op>>) -> Self {
532 Self {
533 shared,
534 brand: std::marker::PhantomData,
535 }
536 }
537
538 pub(crate) fn lock(&self) -> std::sync::MutexGuard<'id, Shared<Op>> {
539 self.shared
540 .lock()
541 .unwrap_or_else(std::sync::PoisonError::into_inner)
542 }
543
544 /// End the reply with what the provider sent at its end. It consumes the
545 /// writer: nothing is written after the end.
546 pub fn end(self, end: Op::End) -> Flow {
547 let mut shared = self.lock();
548 <Op::Emit as reply::Closing<Op>>::close(&mut shared);
549 shared.end = Some(end);
550 Flow::Ended(Ended(()))
551 }
552
553 /// Record the reply's provider document, the response's `raw`, for any
554 /// operation. A whole JSON body the transport reported outranks it, and
555 /// a `raw` the decoder writes onto its response is replaced: a decoder
556 /// whose reply is not one JSON document records it here.
557 pub fn raw(&mut self, raw: serde_json::Value) {
558 self.lock().raw = Some(raw);
559 }
560
561 /// A payload the provider sent that this decoder does not model. It
562 /// reaches the consumer as [`Item::Unknown`](crate::streaming::Item).
563 pub fn unknown(&mut self, payload: crate::streaming::UnknownPayload) {
564 self.lock()
565 .items
566 .push_back(Ok(crate::streaming::Item::Unknown(payload)));
567 }
568}
569
570impl<Op: Operation<Emit = Free>> Out<'_, Op> {
571 /// One event of the reply.
572 ///
573 /// Only an operation whose decoders build their own events has this; a
574 /// completion's events come from its part handles:
575 ///
576 /// ```compile_fail,E0599
577 /// use rig_core::operation::Completion;
578 /// use rig_core::streaming::StreamEvent;
579 /// use rig_core::wire::Out;
580 ///
581 /// fn reinject(out: &mut Out<'_, Completion>, seen: &StreamEvent) {
582 /// out.event(seen.clone());
583 /// }
584 /// ```
585 ///
586 /// An event rebuilt from its serialized form is no different:
587 ///
588 /// ```compile_fail,E0599
589 /// use rig_core::operation::Completion;
590 /// use rig_core::streaming::Transcript;
591 /// use rig_core::wire::Out;
592 ///
593 /// fn rebuild(out: &mut Out<'_, Completion>, recorded: serde_json::Value) {
594 /// let Ok(transcript) = Transcript::parse(recorded) else { return };
595 /// for event in transcript.events() {
596 /// out.event(event.clone());
597 /// }
598 /// }
599 /// ```
600 pub fn event(&mut self, event: Op::Event) {
601 self.lock()
602 .items
603 .push_back(Ok(crate::streaming::Item::Event(event)));
604 }
605}
606
607/// Synchronous state machine for one reply. It classifies frames and
608/// decodes known events into the reply's writer, without transport access
609/// and without being told how the reply arrives. HTTP wires read
610/// [`WireFrame`]s; other transports name their own frame type.
611pub trait Decoder<'id, Op: Operation, Frame = WireFrame> {
612 /// The wire's typed event, produced by this decoder's classifier.
613 type Event;
614
615 /// Decode and classify one frame. A JSON wire MUST delegate to a
616 /// classifier in [`crate::providers::internal::wire`], so the
617 /// decode-then-validate policy is not re-derived per provider.
618 fn classify(&self, frame: Frame) -> WireEvent<Self::Event>;
619
620 /// Write one `Known` event into the reply. An error ends the reply with
621 /// it.
622 fn decode(&mut self, event: Self::Event, out: Out<'id, Op>) -> Result<Flow, ProviderError>;
623
624 /// The frames ran out without an end. A decoder that already saw the
625 /// provider's end, in a form the provider sends before its last frame,
626 /// ends the reply here; otherwise the reply is truncated.
627 fn eof(&mut self, out: Out<'id, Op>) -> Result<Flow, ProviderError> {
628 let _ = out;
629 Err(ProviderError::Truncated)
630 }
631}
632
633/// A provider endpoint: plain data that encodes requests and names a decoder
634/// for each reply.
635///
636/// No transport, no future, no type parameter. Implementations are plain
637/// data (`Clone + PartialEq + Debug + Serialize + Deserialize`, with
638/// credentials held in [`Secret`]), so a host can store one in a scene, a
639/// component, or a config file. `Clone` is a supertrait: the driver clones
640/// the wire into every call's `'static` stream.
641pub trait Wire: Clone + WasmCompatSend + WasmCompatSync + 'static {
642 /// The operation this wire performs.
643 type Op: Operation;
644 /// What [`Self::encode`] produces for the transport to send.
645 type Payload: WasmCompatSend + 'static;
646 /// One unit of a reply, as the transport delivers it.
647 type Frame: WasmCompatSend + 'static;
648 /// The decoder for one of its replies, branded with that reply.
649 type Decoder<'id>: Decoder<'id, Self::Op, Self::Frame> + WasmCompatSend;
650
651 /// What the wire says about itself.
652 fn describe(&self) -> Descriptor<'_>;
653
654 /// The request to send. Pure: it may read `self`, `request` and `mode`,
655 /// and nothing else. A request that cannot be built is an
656 /// [`EncodeError`], which always reports as a request failure.
657 fn encode(&self, request: Request<Self>, mode: Mode) -> Result<Self::Payload, EncodeError>;
658
659 /// A fresh decoder for one reply.
660 fn decoder<'id>(&self) -> Self::Decoder<'id>;
661}
662
663/// The decoder of a reply that is one JSON document: the document is the
664/// operation's end, and is kept as the reply's `raw`.
665#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
666pub struct Json;
667
668impl<'id, Op> Decoder<'id, Op, WireFrame> for Json
669where
670 Op: Operation,
671 Op::End: serde::de::DeserializeOwned,
672{
673 type Event = (Op::End, serde_json::Value);
674
675 fn classify(&self, frame: WireFrame) -> WireEvent<Self::Event> {
676 // Read from the text, so an end holding raw JSON can borrow it.
677 let text = frame.as_str();
678 let document = match serde_json::from_str::<serde_json::Value>(&text) {
679 Ok(document) => document,
680 Err(error) => return WireEvent::Corrupt(error),
681 };
682 match serde_json::from_str::<Op::End>(&text) {
683 Ok(end) => WireEvent::Known((end, document)),
684 Err(error) => WireEvent::Corrupt(error),
685 }
686 }
687
688 fn decode(
689 &mut self,
690 (end, document): Self::Event,
691 mut out: Out<'id, Op>,
692 ) -> Result<Flow, ProviderError> {
693 out.raw(document);
694 Ok(out.end(end))
695 }
696}
697
698/// A wire's request type.
699pub type Request<W> = <<W as Wire>::Op as Operation>::Request;
700/// A wire's response type.
701pub type Response<W> = <<W as Wire>::Op as Operation>::Response;
702/// A wire's event type.
703pub type Event<W> = <<W as Wire>::Op as Operation>::Event;