Skip to main content

stateknot_integrations/
adapter.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4use std::{
5    fmt,
6    io::{self, Write},
7    sync::Arc,
8    time::Instant,
9};
10
11use futures_util::StreamExt;
12use reqwest::{Response, StatusCode, header::HeaderMap};
13use serde::Serialize;
14use serde_json::{Value, json};
15use stateknot_core::{
16    BoundedJson, BoxStream, ContentPart, DurationMillis, ExecutionCount, Extensions, Failure,
17    FailureCategory, FailureCode, FailureId, FailureMessage, FailureOrigin,
18    GraphSchemaValidationError, InstructionContent, JsonLimits, ModelContext, ModelDescriptor,
19    ModelError, ModelErrorPhase, ModelErrorProvenance, ModelEvent, ModelEventAccumulator,
20    ModelEventKind, ModelModality, ModelProviderModelId, ModelProviderRequestId,
21    ModelProviderResponseId, ModelRequest, ModelResponseMode, ModelSchemaRegistry, ModelStopReason,
22    ModelToolOutcome, ModelUsage, RetryAdvice, SchemaReference, SecurityLabel,
23};
24use thiserror::Error;
25
26use crate::{
27    ApiKey, ApiKeyProvider, ApiKeyResolutionError, ProviderEndpoint, ProviderEndpointError,
28    ProviderHttpOptions, http::build_client,
29};
30
31#[derive(Clone, Copy, Debug, Eq, PartialEq)]
32pub(crate) enum ProviderKind {
33    OpenAi,
34    Anthropic,
35}
36
37impl ProviderKind {
38    const fn origin(self) -> &'static str {
39        match self {
40            Self::OpenAi => "provider.openai",
41            Self::Anthropic => "provider.anthropic",
42        }
43    }
44
45    const fn path(self) -> &'static str {
46        match self {
47            Self::OpenAi => "responses",
48            Self::Anthropic => "messages",
49        }
50    }
51}
52
53#[derive(Clone)]
54pub(crate) struct AdapterCore {
55    pub(crate) descriptor: ModelDescriptor,
56    pub(crate) model_id: ModelProviderModelId,
57    pub(crate) output_label: SecurityLabel,
58    pub(crate) schemas: Arc<dyn ModelSchemaRegistry>,
59    credentials: Arc<dyn ApiKeyProvider>,
60    endpoint: ProviderEndpoint,
61    pub(crate) options: ProviderHttpOptions,
62    pub(crate) client: reqwest::Client,
63    pub(crate) kind: ProviderKind,
64}
65
66impl AdapterCore {
67    #[allow(clippy::too_many_arguments)]
68    pub(crate) fn new(
69        descriptor: ModelDescriptor,
70        model_id: ModelProviderModelId,
71        output_label: SecurityLabel,
72        schemas: Arc<dyn ModelSchemaRegistry>,
73        credentials: Arc<dyn ApiKeyProvider>,
74        endpoint: ProviderEndpoint,
75        options: ProviderHttpOptions,
76        kind: ProviderKind,
77    ) -> Result<Self, ModelAdapterBuildError> {
78        if descriptor.capabilities().input_modalities().len() != 1
79            || !descriptor
80                .capabilities()
81                .input_modalities()
82                .contains(ModelModality::Text)
83            || descriptor.capabilities().output_modalities().len() != 1
84            || !descriptor
85                .capabilities()
86                .output_modalities()
87                .contains(ModelModality::Text)
88        {
89            return Err(ModelAdapterBuildError::TextOnlyBindingRequired);
90        }
91        for profile in [
92            descriptor.capabilities().tools().schema_profile(),
93            descriptor
94                .capabilities()
95                .structured_output()
96                .schema_profile(),
97        ]
98        .into_iter()
99        .flatten()
100        {
101            if schemas.canonical_schema_bytes(profile).is_none() {
102                return Err(ModelAdapterBuildError::SchemaProfileUnavailable);
103            }
104        }
105        if kind == ProviderKind::Anthropic
106            && descriptor.capabilities().supports_reasoning_summaries()
107        {
108            return Err(ModelAdapterBuildError::AnthropicReasoningSummariesUnsupported);
109        }
110        let client = build_client(options).map_err(|_| ModelAdapterBuildError::HttpClient)?;
111        endpoint
112            .join(kind.path())
113            .map_err(ModelAdapterBuildError::Endpoint)?;
114        Ok(Self {
115            descriptor,
116            model_id,
117            output_label,
118            schemas,
119            credentials,
120            endpoint,
121            options,
122            client,
123            kind,
124        })
125    }
126
127    pub(crate) fn url(&self) -> reqwest::Url {
128        self.endpoint
129            .join(self.kind.path())
130            .expect("adapter endpoint path was validated during construction")
131    }
132
133    pub(crate) fn preflight(
134        &self,
135        context: &ModelContext,
136        request: &ModelRequest,
137        mode: ModelResponseMode,
138    ) -> Result<(), ModelError> {
139        if request.response_mode() != mode {
140            return Err(self.error(
141                context,
142                ModelErrorPhase::Preparation,
143                FailureCategory::InvalidInput,
144                "request.response_mode",
145                "The model request selected the wrong delivery mode.",
146                RetryAdvice::Never,
147                None,
148                None,
149                None,
150            ));
151        }
152        if self
153            .descriptor
154            .capabilities()
155            .satisfies(request.requirements())
156            .is_err()
157        {
158            return Err(self.error(
159                context,
160                ModelErrorPhase::Preparation,
161                FailureCategory::Unsupported,
162                "request.capability_mismatch",
163                "The model binding does not satisfy this request.",
164                RetryAdvice::Never,
165                None,
166                None,
167                None,
168            ));
169        }
170        if !request.extensions().is_empty() {
171            return Err(self.unsupported_request(context, "request.extensions"));
172        }
173        if request
174            .instructions()
175            .iter()
176            .any(|instruction| matches!(instruction.content(), InstructionContent::Artifact(_)))
177            || request.messages().iter().any(|message| {
178                message
179                    .parts()
180                    .iter()
181                    .any(|part| matches!(part, ContentPart::Artifact(_)))
182            })
183        {
184            return Err(self.unsupported_request(context, "request.artifact_input"));
185        }
186        if request
187            .messages()
188            .iter()
189            .any(|message| message.role() == stateknot_core::MessageRole::Tool)
190        {
191            return Err(self.unsupported_request(context, "request.tool_result_history"));
192        }
193        self.validate_transcript(context, request)?;
194
195        if let Some(schema) = request
196            .text_output_format()
197            .and_then(|format| format.schema())
198        {
199            let Some(profile) = self
200                .descriptor
201                .capabilities()
202                .structured_output()
203                .schema_profile()
204            else {
205                return Err(self.unsupported_request(context, "request.output_schema"));
206            };
207            self.validate_schema_document(context, profile, schema)?;
208        }
209        if request.tools().len() > 0 {
210            let Some(profile) = self.descriptor.capabilities().tools().schema_profile() else {
211                return Err(self.unsupported_request(context, "request.tool_schema"));
212            };
213            for tool in request.tools() {
214                self.validate_schema_document(context, profile, tool.input_schema())?;
215            }
216        }
217        Ok(())
218    }
219
220    fn validate_transcript(
221        &self,
222        context: &ModelContext,
223        request: &ModelRequest,
224    ) -> Result<(), ModelError> {
225        if request
226            .transcript()
227            .model()
228            .is_some_and(|model| model != self.descriptor.metadata().identity())
229        {
230            return Err(self.error(
231                context,
232                ModelErrorPhase::Preparation,
233                FailureCategory::InvalidInput,
234                "request.transcript_model",
235                "The model transcript belongs to another model binding.",
236                RetryAdvice::Never,
237                None,
238                None,
239                None,
240            ));
241        }
242        if request
243            .transcript()
244            .into_iter()
245            .any(|turn| turn.response().provenance().provider_model_id() != Some(&self.model_id))
246        {
247            return Err(self.error(
248                context,
249                ModelErrorPhase::Preparation,
250                FailureCategory::InvalidInput,
251                "request.transcript_provider_model",
252                "The model transcript belongs to another provider model binding.",
253                RetryAdvice::Never,
254                None,
255                None,
256                None,
257            ));
258        }
259        Ok(())
260    }
261
262    fn validate_schema_document(
263        &self,
264        context: &ModelContext,
265        profile: &SchemaReference,
266        schema: &SchemaReference,
267    ) -> Result<(), ModelError> {
268        let Some(bytes) = self.schemas.canonical_schema_bytes(schema) else {
269            return Err(self.schema_error(context, "schema.unavailable"));
270        };
271        let document = BoundedJson::from_slice_with_limits(bytes, JsonLimits::MAXIMUM)
272            .map_err(|_| self.schema_error(context, "schema.invalid_document"))?;
273        match self.schemas.validate(profile, &document) {
274            Ok(()) => Ok(()),
275            Err(GraphSchemaValidationError::Rejected) => {
276                Err(self.schema_error(context, "schema.profile_rejected"))
277            }
278            Err(GraphSchemaValidationError::Unavailable) => {
279                Err(self.schema_error(context, "schema.profile_unavailable"))
280            }
281            Err(_) => Err(self.schema_error(context, "schema.profile_unknown_failure")),
282        }
283    }
284
285    pub(crate) fn schema_value(
286        &self,
287        context: &ModelContext,
288        schema: &SchemaReference,
289    ) -> Result<Value, ModelError> {
290        let bytes = self
291            .schemas
292            .canonical_schema_bytes(schema)
293            .ok_or_else(|| self.schema_error(context, "schema.unavailable"))?;
294        BoundedJson::from_slice_with_limits(bytes, JsonLimits::MAXIMUM)
295            .map(|value| value.as_value().clone())
296            .map_err(|_| self.schema_error(context, "schema.invalid_document"))
297    }
298
299    fn schema_error(&self, context: &ModelContext, code: &'static str) -> ModelError {
300        self.error(
301            context,
302            ModelErrorPhase::Preparation,
303            FailureCategory::InvalidInput,
304            code,
305            "A pinned model schema could not be used safely.",
306            RetryAdvice::Never,
307            None,
308            None,
309            None,
310        )
311    }
312
313    pub(crate) fn unsupported_request(
314        &self,
315        context: &ModelContext,
316        code: &'static str,
317    ) -> ModelError {
318        self.error(
319            context,
320            ModelErrorPhase::Preparation,
321            FailureCategory::Unsupported,
322            code,
323            "The provider adapter cannot represent this request without losing semantics.",
324            RetryAdvice::Never,
325            None,
326            None,
327            None,
328        )
329    }
330
331    pub(crate) fn corrupt_transcript_replay(&self, context: &ModelContext) -> ModelError {
332        self.error(
333            context,
334            ModelErrorPhase::Preparation,
335            FailureCategory::DataCorruption,
336            "request.transcript_replay_corrupt",
337            "The provider replay evidence does not match the normalized model response.",
338            RetryAdvice::Never,
339            None,
340            None,
341            None,
342        )
343    }
344
345    pub(crate) async fn resolve_key(&self, context: &ModelContext) -> Result<ApiKey, ModelError> {
346        let resolved = wait_for(context, self.credentials.resolve(context)).await;
347        match resolved {
348            Ok(Ok(key)) => Ok(key),
349            Ok(Err(ApiKeyResolutionError::Unavailable)) => Err(self.error(
350                context,
351                ModelErrorPhase::Preparation,
352                FailureCategory::DependencyUnavailable,
353                "credential.unavailable",
354                "The provider credential source is temporarily unavailable.",
355                RetryAdvice::SafeAfter {
356                    delay: DurationMillis::new(250).expect("positive constant"),
357                },
358                None,
359                None,
360                None,
361            )),
362            Ok(Err(ApiKeyResolutionError::PermissionDenied)) => Err(self.error(
363                context,
364                ModelErrorPhase::Preparation,
365                FailureCategory::PermissionDenied,
366                "credential.permission_denied",
367                "Provider credential access was denied.",
368                RetryAdvice::Never,
369                None,
370                None,
371                None,
372            )),
373            Err(reason) => Err(self.stop_error(context, ModelErrorPhase::Preparation, reason)),
374        }
375    }
376
377    #[allow(clippy::too_many_arguments)]
378    pub(crate) fn error(
379        &self,
380        context: &ModelContext,
381        phase: ModelErrorPhase,
382        category: FailureCategory,
383        code: &'static str,
384        message: &'static str,
385        retry: RetryAdvice,
386        provider_request_id: Option<ModelProviderRequestId>,
387        provider_response_id: Option<ModelProviderResponseId>,
388        usage: Option<ModelUsage>,
389    ) -> ModelError {
390        let failure = Failure::new(
391            FailureId::generate(),
392            category,
393            FailureCode::new(code).expect("adapter failure code constants are valid"),
394            FailureOrigin::new(self.kind.origin())
395                .expect("adapter failure origin constants are valid"),
396            FailureMessage::new(message).expect("adapter public messages are valid"),
397            retry,
398        )
399        .expect("adapter category and retry constants are coherent");
400        ModelError::new(
401            failure,
402            phase,
403            ModelErrorProvenance::new(
404                context.attempt_id(),
405                self.descriptor.metadata().identity().clone(),
406                Some(self.model_id.clone()),
407                provider_request_id,
408                provider_response_id,
409            ),
410            usage,
411        )
412    }
413
414    pub(crate) fn stop_error(
415        &self,
416        context: &ModelContext,
417        phase: ModelErrorPhase,
418        reason: ModelStopReason,
419    ) -> ModelError {
420        let (category, code, message) = match reason {
421            ModelStopReason::Cancelled => (
422                FailureCategory::Cancelled,
423                "request.cancelled",
424                "The model attempt was cancelled.",
425            ),
426            ModelStopReason::DeadlineExceeded => (
427                FailureCategory::DeadlineExceeded,
428                "request.deadline_exceeded",
429                "The model attempt exceeded its deadline.",
430            ),
431            _ => (
432                FailureCategory::Internal,
433                "request.unknown_stop_reason",
434                "The model attempt stopped for an unsupported reason.",
435            ),
436        };
437        self.error(
438            context,
439            phase,
440            category,
441            code,
442            message,
443            RetryAdvice::Never,
444            None,
445            None,
446            None,
447        )
448    }
449
450    pub(crate) fn status_error(
451        &self,
452        context: &ModelContext,
453        phase: ModelErrorPhase,
454        status: StatusCode,
455        headers: &HeaderMap,
456        provider_request_id: Option<ModelProviderRequestId>,
457    ) -> ModelError {
458        let (category, code, message, retry) = match status.as_u16() {
459            400 | 413 | 422 => (
460                FailureCategory::InvalidInput,
461                "http.invalid_request",
462                "The model provider rejected the request.",
463                RetryAdvice::Never,
464            ),
465            401 => (
466                FailureCategory::Unauthenticated,
467                "http.unauthenticated",
468                "The model provider rejected authentication.",
469                RetryAdvice::Never,
470            ),
471            403 => (
472                FailureCategory::PermissionDenied,
473                "http.permission_denied",
474                "The model provider denied this operation.",
475                RetryAdvice::Never,
476            ),
477            404 => (
478                FailureCategory::NotFound,
479                "http.not_found",
480                "The configured model provider resource was not found.",
481                RetryAdvice::Never,
482            ),
483            429 => (
484                FailureCategory::RateLimited,
485                "http.rate_limited",
486                "The model provider rate limit prevented execution.",
487                parse_retry_after(headers)
488                    .map_or(RetryAdvice::Never, |delay| RetryAdvice::SafeAfter { delay }),
489            ),
490            500..=599 => (
491                FailureCategory::DependencyUnavailable,
492                "http.provider_unavailable",
493                "The model provider is temporarily unavailable.",
494                RetryAdvice::SafeAfter {
495                    delay: DurationMillis::new(250).expect("positive constant"),
496                },
497            ),
498            _ => (
499                FailureCategory::DependencyUnavailable,
500                "http.unexpected_status",
501                "The model provider returned an unsupported status.",
502                RetryAdvice::Never,
503            ),
504        };
505        self.error(
506            context,
507            phase,
508            category,
509            code,
510            message,
511            retry,
512            provider_request_id,
513            None,
514            None,
515        )
516    }
517
518    pub(crate) fn transport_error(
519        &self,
520        context: &ModelContext,
521        phase: ModelErrorPhase,
522    ) -> ModelError {
523        self.error(
524            context,
525            phase,
526            FailureCategory::DependencyUnavailable,
527            "http.transport",
528            "The model provider transport failed.",
529            RetryAdvice::Never,
530            None,
531            None,
532            None,
533        )
534    }
535
536    pub(crate) fn malformed_error(
537        &self,
538        context: &ModelContext,
539        phase: ModelErrorPhase,
540        provider_request_id: Option<ModelProviderRequestId>,
541        provider_response_id: Option<ModelProviderResponseId>,
542        usage: Option<ModelUsage>,
543    ) -> ModelError {
544        self.error(
545            context,
546            phase,
547            FailureCategory::DataCorruption,
548            "response.malformed",
549            "The model provider returned a malformed response.",
550            RetryAdvice::Never,
551            provider_request_id,
552            provider_response_id,
553            usage,
554        )
555    }
556}
557
558impl fmt::Debug for AdapterCore {
559    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
560        formatter
561            .debug_struct("AdapterCore")
562            .field("descriptor", &self.descriptor)
563            .field("model_id", &self.model_id)
564            .field("endpoint", &self.endpoint)
565            .field("options", &self.options)
566            .field("provider", &self.kind)
567            .finish_non_exhaustive()
568    }
569}
570
571/// Invalid first-party model adapter construction.
572#[derive(Clone, Debug, Eq, Error, PartialEq)]
573#[non_exhaustive]
574pub enum ModelAdapterBuildError {
575    /// The descriptor included a modality not implemented by this binding.
576    #[error("first-party v1 provider adapters require text-only input and output bindings")]
577    TextOnlyBindingRequired,
578    /// A descriptor schema profile was not installed in the offline registry.
579    #[error("model descriptor schema profile is unavailable in the offline registry")]
580    SchemaProfileUnavailable,
581    /// The current Anthropic adapter does not expose readable reasoning summaries.
582    #[error("Anthropic reasoning summaries are not supported by this adapter version")]
583    AnthropicReasoningSummariesUnsupported,
584    /// Secure client construction failed.
585    #[error("provider HTTP client construction failed")]
586    HttpClient,
587    /// The fixed provider route could not be joined.
588    #[error("invalid provider endpoint: {0}")]
589    Endpoint(ProviderEndpointError),
590}
591
592pub(crate) async fn wait_for<T, F>(context: &ModelContext, future: F) -> Result<T, ModelStopReason>
593where
594    F: std::future::Future<Output = T>,
595{
596    if let Some(reason) = context.stop_reason_at(Instant::now()) {
597        return Err(reason);
598    }
599    let deadline = tokio::time::Instant::from_std(context.deadline_instant());
600    tokio::select! {
601        biased;
602        () = context.cancellation().cancelled() => Err(ModelStopReason::Cancelled),
603        () = tokio::time::sleep_until(deadline) => {
604            Err(context.stop_reason_at(Instant::now()).unwrap_or(ModelStopReason::DeadlineExceeded))
605        }
606        output = future => Ok(output),
607    }
608}
609
610pub(crate) async fn bounded_body(
611    core: &AdapterCore,
612    context: &ModelContext,
613    response: Response,
614    maximum: usize,
615    phase: ModelErrorPhase,
616) -> Result<Vec<u8>, ModelError> {
617    let mut body = Vec::new();
618    let mut stream = response.bytes_stream();
619    loop {
620        let next = wait_for(context, stream.next())
621            .await
622            .map_err(|reason| core.stop_error(context, phase, reason))?;
623        let Some(chunk) = next else {
624            break;
625        };
626        let chunk = chunk.map_err(|_| core.transport_error(context, phase))?;
627        if body.len().saturating_add(chunk.len()) > maximum {
628            return Err(core.error(
629                context,
630                phase,
631                FailureCategory::DataCorruption,
632                "response.too_large",
633                "The model provider response exceeded its configured byte ceiling.",
634                RetryAdvice::Never,
635                None,
636                None,
637                None,
638            ));
639        }
640        body.extend_from_slice(&chunk);
641    }
642    Ok(body)
643}
644
645pub(crate) fn serialize_request<T: Serialize>(
646    core: &AdapterCore,
647    context: &ModelContext,
648    value: &T,
649) -> Result<Vec<u8>, ModelError> {
650    let mut writer = RequestBodyWriter::new(core.options.maximum_request_bytes());
651    if serde_json::to_writer(&mut writer, value).is_err() {
652        return Err(if writer.overflowed {
653            core.error(
654                context,
655                ModelErrorPhase::Preparation,
656                FailureCategory::InvalidInput,
657                "request.too_large",
658                "The serialized model request exceeded its configured byte ceiling.",
659                RetryAdvice::Never,
660                None,
661                None,
662                None,
663            )
664        } else {
665            core.malformed_error(context, ModelErrorPhase::Preparation, None, None, None)
666        });
667    }
668    Ok(writer.bytes)
669}
670
671struct RequestBodyWriter {
672    bytes: Vec<u8>,
673    maximum: usize,
674    overflowed: bool,
675}
676
677impl RequestBodyWriter {
678    fn new(maximum: usize) -> Self {
679        Self {
680            bytes: Vec::with_capacity(maximum.min(4096)),
681            maximum,
682            overflowed: false,
683        }
684    }
685}
686
687impl Write for RequestBodyWriter {
688    fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
689        let Some(length) = self.bytes.len().checked_add(buffer.len()) else {
690            self.overflowed = true;
691            return Err(io::Error::other("provider request byte limit exceeded"));
692        };
693        if length > self.maximum {
694            self.overflowed = true;
695            return Err(io::Error::other("provider request byte limit exceeded"));
696        }
697        self.bytes.extend_from_slice(buffer);
698        Ok(buffer.len())
699    }
700
701    fn flush(&mut self) -> io::Result<()> {
702        Ok(())
703    }
704}
705
706pub(crate) fn parse_provider_request_id(headers: &HeaderMap) -> Option<ModelProviderRequestId> {
707    headers
708        .get("x-request-id")
709        .and_then(|value| value.to_str().ok())
710        .and_then(|value| ModelProviderRequestId::new(value).ok())
711}
712
713fn parse_retry_after(headers: &HeaderMap) -> Option<DurationMillis> {
714    const MAX_RETRY_SECONDS: u64 = 86_400;
715    let seconds = headers
716        .get("retry-after")?
717        .to_str()
718        .ok()?
719        .parse::<u64>()
720        .ok()?;
721    if seconds > MAX_RETRY_SECONDS {
722        return None;
723    }
724    let millis = seconds.checked_mul(1000)?;
725    DurationMillis::try_from(millis).ok()
726}
727
728pub(crate) fn empty_extensions() -> Extensions {
729    Extensions::default()
730}
731
732pub(crate) fn model_tool_outcome_payload(outcome: &ModelToolOutcome) -> Value {
733    if let Some(result) = outcome.result() {
734        return result.output().as_value().clone();
735    }
736    let error = outcome
737        .error()
738        .expect("closed model tool outcome is either a result or an error");
739    json!({
740        "error": {
741            "id": error.failure_id(),
742            "category": error.category(),
743            "code": error.code(),
744            "message": error.message(),
745            "retry_advice": error.retry_advice(),
746            "external_effect": error.external_effect(),
747        }
748    })
749}
750
751pub(crate) struct EventEmitter<'a> {
752    core: &'a AdapterCore,
753    context: &'a ModelContext,
754    accumulator: ModelEventAccumulator<'a>,
755    next_sequence: u64,
756    sender: tokio::sync::mpsc::Sender<Result<ModelEvent, ModelError>>,
757}
758
759impl<'a> EventEmitter<'a> {
760    pub(crate) fn new(
761        core: &'a AdapterCore,
762        context: &'a ModelContext,
763        request: &'a ModelRequest,
764        sender: tokio::sync::mpsc::Sender<Result<ModelEvent, ModelError>>,
765    ) -> Result<Self, ModelError> {
766        let accumulator =
767            ModelEventAccumulator::new(context.attempt_id(), &core.descriptor, request).map_err(
768                |_| core.malformed_error(context, ModelErrorPhase::Preparation, None, None, None),
769            )?;
770        Ok(Self {
771            core,
772            context,
773            accumulator,
774            next_sequence: 0,
775            sender,
776        })
777    }
778
779    pub(crate) async fn emit(&mut self, kind: ModelEventKind) -> Result<(), EmitError> {
780        let event = ModelEvent::new(
781            self.context.attempt_id(),
782            ExecutionCount::new(self.next_sequence),
783            kind,
784        )
785        .map_err(|_| EmitError::Invalid(self.invalid()))?;
786        self.accumulator
787            .push(event.clone())
788            .map_err(|_| EmitError::Invalid(self.invalid()))?;
789        self.sender.send(Ok(event)).await.map_err(|_| {
790            EmitError::Invalid(self.core.stop_error(
791                self.context,
792                ModelErrorPhase::Stream,
793                ModelStopReason::Cancelled,
794            ))
795        })?;
796        self.next_sequence = self
797            .next_sequence
798            .checked_add(1)
799            .ok_or_else(|| EmitError::Invalid(self.invalid()))?;
800        Ok(())
801    }
802
803    pub(crate) fn is_complete(&self) -> bool {
804        self.accumulator.is_complete()
805    }
806
807    fn invalid(&self) -> ModelError {
808        self.core
809            .malformed_error(self.context, ModelErrorPhase::Stream, None, None, None)
810    }
811}
812
813pub(crate) enum EmitError {
814    Invalid(ModelError),
815}
816
817pub(crate) fn receiver_stream(
818    receiver: tokio::sync::mpsc::Receiver<Result<ModelEvent, ModelError>>,
819) -> BoxStream<'static, Result<ModelEvent, ModelError>> {
820    Box::pin(futures_util::stream::unfold(
821        receiver,
822        |mut receiver| async move { receiver.recv().await.map(|item| (item, receiver)) },
823    ))
824}