Skip to main content

harmos_sdk/operations/
serving.rs

1/* ***
2 *
3 * Harmos
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * ***
8 */
9
10/* === Modules === */
11
12mod codec;
13mod owned;
14#[cfg(feature = "grpc")]
15pub(crate) mod protobuf;
16#[cfg(feature = "streaming")]
17mod streams;
18
19/* === Re-Exports === */
20
21pub use codec::WireCodecError;
22#[cfg(feature = "streaming")]
23pub use streams::{WireEndpoints, WireStreamLimits, WireStreams};
24
25/* === Imports === */
26
27// Standard Library Imports
28use std::collections::BTreeMap;
29use std::future::Future;
30use std::num::NonZeroUsize;
31use std::pin::Pin;
32use std::sync::{Arc, Mutex, Weak};
33use std::task::{Poll, Waker};
34// Third Party Imports
35use serde::{Deserialize, Serialize};
36use tracing::Instrument;
37// Local Imports
38use super::{Contract, ContractError, ExecutionContext, FailureKind, OperationDefinition, RegistrationBatch};
39use crate::QualifiedId;
40
41/* === Constants === */
42
43pub const WIRE_METHOD: &str = "harmos.operation.v2";
44
45pub const CHILD_METHOD: &str = "harmos.operation.child.v2";
46
47/* === Macros === */
48
49/* === Type Aliases === */
50
51type Answer<'a> = Pin<Box<dyn Future<Output = Result<Vec<u8>, ServingError>> + Send + 'a>>;
52type Finished<'a> = Pin<Box<dyn Future<Output = Result<(), ServingError>> + Send + 'a>>;
53type Finalization<S> = Pin<Box<dyn Future<Output = (S, Result<(), ServingError>)> + Send + 'static>>;
54type Prepare = Box<dyn Fn(Vec<u8>, bool) -> Result<Box<dyn Prepared>, ServingError> + Send + Sync>;
55
56/* === Structs === */
57
58struct Contextual<F: std::future::Future> {
59    future: Option<std::pin::Pin<Box<F>>>,
60    dispatcher: tracing::Dispatch,
61}
62
63#[derive(Debug, Serialize, Deserialize)]
64#[serde(deny_unknown_fields)]
65pub struct WireChildCall {
66    pub context: [u8; 32],
67
68    #[serde(default, skip_serializing_if = "Option::is_none")]
69    pub generation_context: Option<[u8; 32]>,
70
71    #[serde(default, skip_serializing_if = "Vec::is_empty")]
72    pub values: Vec<super::CallValue>,
73
74    pub operation: String,
75    pub fingerprint: [u8; 32],
76    pub generation: u64,
77    pub payload: Vec<u8>,
78
79    // Submitted children answer their instance id at admission and remain
80    // owned by the calling attempt until joined, released or detached.
81    #[serde(default)]
82    pub submit: bool,
83}
84
85// Drives one child the same attempt submitted; the host resolves the instance
86// only inside the attempt context that submitted it.
87#[derive(Debug, Serialize, Deserialize)]
88#[serde(deny_unknown_fields)]
89pub struct WireChildControl {
90    pub context: [u8; 32],
91    pub instance: u64,
92    pub action: WireChildAction,
93}
94
95pub struct WireTable {
96    owner: String,
97    handlers: BTreeMap<String, Route>,
98    retired: BTreeMap<String, u64>,
99    services: BTreeMap<String, super::registration::ServiceFactory>,
100    prepared: BTreeMap<u64, Arc<Slot>>,
101    capacity: Option<NonZeroUsize>,
102    closed: bool,
103    ordinary_closed: bool,
104    provided: Vec<std::any::TypeId>,
105
106    #[cfg(feature = "streaming")]
107    stream_limits: Option<WireStreamLimits>,
108}
109
110struct Slot {
111    operation: String,
112    lifecycle: bool,
113    resident: bool,
114
115    #[cfg(feature = "streaming")]
116    streams: Option<WireStreams>,
117
118    state: Mutex<SlotState>,
119}
120
121struct SlotState {
122    prepared: Option<Box<dyn Prepared>>,
123    finished: bool,
124    cancelled: bool,
125    waiters: Vec<Weak<Mutex<Option<Waker>>>>,
126}
127
128struct Loan {
129    slot: Arc<Slot>,
130    prepared: Option<Box<dyn Prepared>>,
131    finished: bool,
132}
133
134struct Route {
135    callees: &'static [super::WireDeclaration],
136    lifecycle: bool,
137    // Lifecycle actions and the observe control are built in: they serve the
138    // plugin's machinery and never appear in its declared catalog.
139    builtin: bool,
140    // A resident control runs until cancelled and is not charged against the
141    // ordinary invocation capacity.
142    resident: bool,
143    definition: OperationDefinition,
144    generation: Option<u64>,
145    closing: bool,
146    contract: Option<Contract>,
147    prepare: Prepare,
148}
149
150/* === Enums === */
151
152// Answers: `Join` the child's response payload, `Status` and `Cancel` an
153// encoded instance state, `Release` and `Detach` an empty payload.
154// Releasing cancels the child; detaching leaves it running without a handle.
155#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
156#[serde(rename_all = "snake_case")]
157pub enum WireChildAction {
158    Join,
159    Status,
160    Cancel,
161    Release,
162    Detach,
163}
164
165#[derive(Debug)]
166pub enum WireChild {
167    Call(WireChildCall),
168    Control(WireChildControl),
169}
170
171#[derive(Debug, Serialize, Deserialize)]
172#[serde(tag = "phase", rename_all = "snake_case", deny_unknown_fields)]
173pub enum WireCommand {
174    Prepare { invocation: u64, operation: String, fingerprint: [u8; 32], generation: u64, payload: Vec<u8> },
175    Initialize { invocation: u64, context: [u8; 32] },
176    Attempt { invocation: u64, context: [u8; 32], values: Vec<super::CallValue> },
177    Finalize { invocation: u64 },
178    StreamAttempt { invocation: u64, epoch: u64, context: [u8; 32], values: Vec<super::CallValue> },
179    StreamSend { invocation: u64, epoch: u64, payload: Vec<u8> },
180    StreamFinish { invocation: u64, epoch: u64 },
181    StreamReceive { invocation: u64, epoch: u64 },
182    PrepareGrpc { invocation: u64, operation: String, fingerprint: [u8; 32], generation: u64, payload: Vec<u8> },
183}
184
185#[derive(Debug, Serialize, Deserialize)]
186#[serde(tag = "status", rename_all = "snake_case", deny_unknown_fields)]
187pub enum WireAnswer {
188    Stream { epoch: u64, transferred: bool, payload: Option<Vec<u8>> },
189    Ready { payload: Vec<u8> },
190    Failed { failure: crate::Failure },
191}
192
193#[derive(Debug, thiserror::Error)]
194pub enum ServingError {
195    #[error("caller may not invoke operation `{operation}` without a host assignment")]
196    Unassigned { operation: &'static str },
197
198    #[error("operation endpoint types differ from the declaration")]
199    EndpointTypes,
200
201    #[error("carrier invocation does not support stream commands")]
202    StreamUnsupported,
203
204    #[cfg(feature = "streaming")]
205    #[error("streaming catalog requires explicit provider stream limits")]
206    StreamLimits,
207
208    #[cfg(feature = "streaming")]
209    #[error("carrier stream failed: {0}")]
210    Stream(#[source] super::streaming::Error),
211
212    #[cfg(feature = "streaming")]
213    #[error("carrier stream direction already has an outstanding request")]
214    StreamBusy,
215
216    #[cfg(feature = "streaming")]
217    #[error("carrier stream direction or attempt is not available")]
218    StreamPhase,
219
220    #[error(transparent)]
221    Lifecycle(#[from] harmos_domain::model::operations::lifecycle::Error),
222
223    #[error(transparent)]
224    Contract(#[from] ContractError),
225
226    #[error(transparent)]
227    Declaration(#[from] crate::Error),
228
229    #[error("operation `{operation}` declares resource `{resource}` that its registration does not provide")]
230    Resource { operation: String, resource: &'static str },
231
232    #[error("operation `{operation}` has no bound carrier handler")]
233    Unknown { operation: String },
234
235    #[error("operation `{operation}` requires streaming endpoints unsupported by this carrier binding")]
236    Streaming { operation: String },
237
238    #[error("operation `{operation}` has a mismatched fingerprint or stale generation")]
239    Identity { operation: String },
240
241    #[error("carrier invocation `{invocation}` is already prepared")]
242    Duplicate { invocation: u64 },
243
244    #[error("carrier invocation `{invocation}` has not been prepared")]
245    Missing { invocation: u64 },
246
247    #[error("carrier operation has not completed initialization")]
248    Uninitialized,
249
250    #[error("carrier operation initialization already started and cannot be replayed")]
251    InitializationStarted,
252
253    #[error("carrier invocation capacity is exhausted")]
254    Capacity,
255
256    #[error("carrier ordinary invocations have not finished settlement")]
257    Unsettled,
258
259    #[error("carrier operation admission is closing")]
260    Closing,
261
262    #[error("carrier handler definitions differ from the selected operation catalog")]
263    Catalog,
264
265    #[error("operation payload codec failed")]
266    Codec(#[source] crate::MessageError),
267
268    #[error("carrier handler panicked")]
269    Panicked,
270
271    // The handler's failure, written once at its origin.
272    #[error(transparent)]
273    Handler(crate::Failure),
274
275    #[error("native handler failed: {0}")]
276    Native(#[source] std::sync::Arc<dyn std::error::Error + Send + Sync>),
277}
278
279/* === Traits === */
280
281trait InContext: std::future::Future + Sized {
282    fn in_context(self, dispatcher: tracing::Dispatch) -> Contextual<Self> {
283        Contextual { future: Some(Box::pin(self)), dispatcher }
284    }
285
286    fn in_current_context(self) -> Contextual<Self> {
287        self.in_context(tracing::dispatcher::get_default(Clone::clone))
288    }
289}
290
291trait Prepared: Send {
292    #[cfg(feature = "streaming")]
293    fn streams(&self) -> Option<WireStreams> {
294        None
295    }
296
297    // The grant the prepared request needs, answered to the host with Prepare.
298    fn grant(&self) -> Option<crate::plugin::Grant> {
299        None
300    }
301    fn bind<'a>(&'a mut self, context: &'a ExecutionContext) -> Finished<'a>;
302    fn attempt<'a>(&'a mut self, context: &'a ExecutionContext) -> Answer<'a>;
303    fn finalize(&mut self) -> Finished<'_>;
304}
305
306/* === Implementations === */
307
308impl<F: std::future::Future> InContext for F {}
309
310impl<F: std::future::Future> std::future::Future for Contextual<F> {
311    type Output = F::Output;
312
313    fn poll(self: std::pin::Pin<&mut Self>, context: &mut std::task::Context<'_>) -> std::task::Poll<Self::Output> {
314        let owner = self.get_mut();
315        let _dispatcher = tracing::dispatcher::set_default(&owner.dispatcher);
316        owner.future.as_mut().expect("context future remains until drop").as_mut().poll(context)
317    }
318}
319
320impl<F: std::future::Future> Drop for Contextual<F> {
321    fn drop(&mut self) {
322        tracing::dispatcher::with_default(&self.dispatcher, || drop(self.future.take()));
323    }
324}
325
326impl WireTable {
327    pub fn new(owner: &str) -> Result<Self, ServingError> {
328        QualifiedId::qualify(owner, "validation").map_err(|_| ServingError::Catalog)?;
329        Ok(Self {
330            owner: owner.to_owned(),
331            services: BTreeMap::new(),
332            handlers: BTreeMap::new(),
333            retired: BTreeMap::new(),
334            prepared: BTreeMap::new(),
335            capacity: None,
336            closed: false,
337            ordinary_closed: false,
338            provided: Vec::new(),
339            #[cfg(feature = "streaming")]
340            stream_limits: None,
341        })
342    }
343
344    // The Carrier Supplies These Resources To Every Attempt's Execution Context.
345    pub fn provide(&mut self, resource: std::any::TypeId) {
346        self.provided.push(resource);
347    }
348
349    pub fn provided(&self) -> &[std::any::TypeId] {
350        &self.provided
351    }
352
353    pub fn capacity(&mut self, capacity: NonZeroUsize) {
354        self.capacity = Some(capacity);
355    }
356
357    #[cfg(feature = "streaming")]
358    pub fn stream_limits(&mut self, limits: WireStreamLimits) -> Result<(), ServingError> {
359        limits.validate()?;
360        self.stream_limits = Some(limits);
361        Ok(())
362    }
363
364    pub fn register(&mut self, batch: RegistrationBatch) -> Result<(), ServingError> {
365        if self.closed || self.ordinary_closed {
366            return Err(ServingError::Closing);
367        }
368        let mut staged = Self::new(&self.owner)?;
369        staged.capacity = self.capacity;
370        staged.provided.clone_from(&self.provided);
371        #[cfg(feature = "streaming")]
372        {
373            staged.stream_limits = self.stream_limits;
374        }
375        for factory in batch.operations {
376            factory.install(&mut staged)?;
377        }
378        for factory in batch.services {
379            factory.policy.validate().map_err(|_| ServingError::Catalog)?;
380            let id = QualifiedId::qualify(&self.owner, &factory.local_id).map_err(|_| ServingError::Catalog)?;
381            let id = id.as_str().to_owned();
382            if staged.handlers.contains_key(&id) || staged.services.insert(id, factory).is_some() {
383                return Err(ServingError::Catalog);
384            }
385        }
386        if staged.handlers.keys().chain(staged.services.keys()).any(|id| self.handlers.contains_key(id) || self.services.contains_key(id)) {
387            return Err(ServingError::Catalog);
388        }
389        self.handlers.append(&mut staged.handlers);
390        self.services.append(&mut staged.services);
391        Ok(())
392    }
393
394    pub async fn unregister(&mut self, id: &QualifiedId) -> Result<(), ServingError> {
395        let key = id.as_str();
396        if !self.handlers.contains_key(key) && !self.services.contains_key(key) {
397            return Err(ServingError::Unknown { operation: key.to_owned() });
398        }
399        if let Some(handler) = self.handlers.get_mut(key) {
400            handler.closing = true;
401        }
402        let slots: Vec<_> =
403            self.prepared.iter().filter(|(_, slot)| slot.operation == key).map(|(invocation, slot)| (*invocation, slot.clone())).collect();
404        for (_, slot) in &slots {
405            slot.cancel();
406        }
407        for (_, slot) in &slots {
408            slot.finalize().await?;
409        }
410        for (invocation, _) in slots {
411            self.prepared.remove(&invocation);
412        }
413        if let Some(handler) = self.handlers.remove(key)
414            && let Some(generation) = handler.generation
415        {
416            self.retired.insert(key.to_owned(), generation);
417        }
418        self.services.remove(key);
419        Ok(())
420    }
421
422    pub fn definitions(&self) -> Vec<OperationDefinition> {
423        self.handlers.values().filter(|handler| !handler.builtin).map(|handler| handler.definition.clone()).collect()
424    }
425
426    pub fn validate(&self, definitions: &[OperationDefinition]) -> Result<(), ServingError> {
427        if definitions.len() != self.handlers.values().filter(|handler| !handler.builtin).count() {
428            return Err(ServingError::Catalog);
429        }
430        for definition in definitions {
431            if self
432                .handlers
433                .get(QualifiedId::qualify(&self.owner, definition.id.as_str()).map_err(|_| ServingError::Catalog)?.as_str())
434                .is_none_or(|bound| bound.builtin || bound.definition != *definition)
435            {
436                return Err(ServingError::Catalog);
437            }
438        }
439        let unique: std::collections::BTreeSet<_> = definitions.iter().map(|definition| &definition.id).collect();
440        if unique.len() != definitions.len() {
441            return Err(ServingError::Catalog);
442        }
443        Ok(())
444    }
445
446    pub fn validate_callees(&self, assignments: &[u8]) -> Result<(), ServingError> {
447        let assignments: Vec<super::AssignedOperation> =
448            if assignments.is_empty() { Vec::new() } else { postcard::from_bytes(assignments).map_err(|_| ServingError::Catalog)? };
449        for route in self.handlers.values() {
450            for callee in route.callees {
451                let id = callee.operation.id;
452                let fingerprint = (callee.operation.fingerprint)().map_err(|_| ServingError::Catalog)?;
453                let local = QualifiedId::qualify(&self.owner, id).map_err(|_| ServingError::Catalog)?;
454                let actual = self
455                    .handlers
456                    .get(local.as_str())
457                    .map(|entry| entry.definition.fingerprint.0)
458                    .or_else(|| {
459                        assignments
460                            .iter()
461                            .find(|entry| entry.operation.split_once('.').is_some_and(|(_, name)| name == id))
462                            .map(|entry| entry.fingerprint)
463                    })
464                    .ok_or(ServingError::Unassigned { operation: id })?;
465                if actual != fingerprint.0 {
466                    return Err(ServingError::Identity { operation: id.to_owned() });
467                }
468            }
469        }
470        Ok(())
471    }
472
473    pub fn validate_contracts(&self, contracts: &[Contract]) -> Result<(), ServingError> {
474        if contracts.len() != self.handlers.values().filter(|handler| !handler.builtin).count() {
475            return Err(ServingError::Catalog);
476        }
477        let mut unique = std::collections::BTreeSet::new();
478        for contract in contracts {
479            let id = &contract.operation().id;
480            if !unique.insert(id)
481                || self
482                    .handlers
483                    .get(QualifiedId::qualify(&self.owner, id.as_str()).map_err(|_| ServingError::Catalog)?.as_str())
484                    .is_none_or(|bound| bound.builtin || bound.contract.as_ref() != Some(contract))
485            {
486                return Err(ServingError::Catalog);
487            }
488        }
489        Ok(())
490    }
491
492    // Answers the request's grant as the Prepare payload.
493    pub fn prepare(
494        &mut self, invocation: u64, operation: &str, fingerprint: [u8; 32], generation: u64, payload: Vec<u8>,
495    ) -> Result<Vec<u8>, ServingError> {
496        self.prepare_codec(invocation, operation, fingerprint, generation, payload, false)
497    }
498
499    fn prepare_codec(
500        &mut self, invocation: u64, operation: &str, fingerprint: [u8; 32], generation: u64, payload: Vec<u8>, grpc: bool,
501    ) -> Result<Vec<u8>, ServingError> {
502        if self.closed {
503            return Err(ServingError::Closing);
504        }
505        self.prepared.retain(|_, slot| !slot.is_finished());
506        if self.prepared.contains_key(&invocation) {
507            return Err(ServingError::Duplicate { invocation });
508        }
509        let handler = self.handlers.get_mut(operation).ok_or_else(|| ServingError::Unknown { operation: operation.to_owned() })?;
510        if handler.definition.fingerprint.0 != fingerprint
511            || generation == 0
512            || handler.generation.is_some_and(|bound| bound != generation)
513            || self.retired.get(operation).is_some_and(|retired| generation <= *retired)
514        {
515            return Err(ServingError::Identity { operation: operation.to_owned() });
516        }
517        // The authenticated host assigns a generation with its first preparation.
518        // Keep it through withdrawal so delayed preparations cannot bind a replacement.
519        handler.generation = Some(generation);
520        if handler.closing || (self.ordinary_closed && !handler.lifecycle) {
521            return Err(ServingError::Closing);
522        }
523        let occupied = self.prepared.values().filter(|slot| slot.lifecycle == handler.lifecycle && !slot.resident).count();
524        // One accounted reserved lifecycle slot remains available even when
525        // ordinary admission is full. Failed SDK finalization retains that slot.
526        let capacity = if handler.lifecycle { 1 } else { self.capacity.ok_or(ServingError::Capacity)?.get() };
527        if occupied >= capacity && !handler.resident {
528            return Err(ServingError::Capacity);
529        }
530        let prepared = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (handler.prepare)(payload, grpc)))
531            .map_err(|_| ServingError::Panicked)??;
532        let answer = encode_prepared_grant(prepared.grant().as_ref());
533        let slot = Slot {
534            operation: operation.to_owned(),
535            lifecycle: handler.lifecycle,
536            resident: handler.resident,
537            #[cfg(feature = "streaming")]
538            streams: prepared.streams(),
539            state: Mutex::new(SlotState {
540                prepared: Some(prepared),
541                finished: false,
542                cancelled: false,
543                waiters: Vec::new(),
544            }),
545        };
546        self.prepared.insert(invocation, Arc::new(slot));
547        Ok(answer)
548    }
549
550    #[cfg(feature = "streaming")]
551    pub fn streams(&self, invocation: u64) -> Result<WireStreams, ServingError> {
552        let slot = self.prepared.get(&invocation).ok_or(ServingError::Missing { invocation })?;
553        if self.closed || (self.ordinary_closed && !slot.lifecycle) || slot.is_finished() {
554            return Err(ServingError::Closing);
555        }
556        slot.streams.clone().ok_or(ServingError::StreamPhase)
557    }
558
559    #[tracing::instrument(target = "harmos::streams", name = "streams.initialize", level = "trace", skip_all, fields(invocation))]
560    pub async fn bind(&mut self, invocation: u64, context: &ExecutionContext) -> Result<(), ServingError> {
561        if self.closed {
562            return Err(ServingError::Closing);
563        }
564        let slot = self.prepared.get(&invocation).ok_or(ServingError::Missing { invocation })?;
565        if self.ordinary_closed && !slot.lifecycle {
566            return Err(ServingError::Closing);
567        }
568        slot.bind(invocation, context).await
569    }
570
571    #[tracing::instrument(target = "harmos::streams", name = "streams.attempt", level = "trace", skip_all, fields(invocation))]
572    pub async fn attempt(&mut self, invocation: u64, context: &ExecutionContext) -> Result<Vec<u8>, ServingError> {
573        if self.closed {
574            return Err(ServingError::Closing);
575        }
576        let slot = self.prepared.get(&invocation).ok_or(ServingError::Missing { invocation })?;
577        if self.ordinary_closed && !slot.lifecycle {
578            return Err(ServingError::Closing);
579        }
580        slot.attempt(invocation, context, None).await
581    }
582
583    #[tracing::instrument(target = "harmos::streams", name = "streams.finalize", level = "trace", skip_all, fields(invocation))]
584    pub async fn finalize(&mut self, invocation: u64) -> Result<(), ServingError> {
585        if let Some(slot) = self.prepared.get(&invocation) {
586            slot.finalize().await?;
587        }
588        self.prepared.remove(&invocation);
589        Ok(())
590    }
591
592    fn traffic(&self, command: WireCommand) -> Pin<Box<dyn Future<Output = WireAnswer> + Send + 'static>> {
593        #[cfg(not(feature = "streaming"))]
594        {
595            let _ = command;
596            Box::pin(async { wire_answer(Err(ServingError::StreamUnsupported)) })
597        }
598        #[cfg(feature = "streaming")]
599        {
600            let invocation = match &command {
601                WireCommand::StreamSend { invocation, .. }
602                | WireCommand::StreamFinish { invocation, .. }
603                | WireCommand::StreamReceive { invocation, .. } => *invocation,
604                _ => unreachable!("only stream traffic bypasses the phase loan"),
605            };
606            let streams = self.streams(invocation);
607            Box::pin(async move {
608                let streams = match streams {
609                    Ok(streams) => streams,
610                    Err(error) => return wire_answer(Err(error)),
611                };
612                match command {
613                    WireCommand::StreamSend { epoch, payload, .. } => {
614                        wire_answer(guarded(async { streams.send(epoch, &payload).await.map(|()| Vec::new()) }).await)
615                    }
616                    WireCommand::StreamFinish { epoch, .. } => wire_answer(streams.finish_input(epoch).map(|()| Vec::new())),
617                    WireCommand::StreamReceive { epoch, .. } => match guarded(streams.receive(epoch)).await {
618                        Ok(payload) => WireAnswer::Stream {
619                            epoch,
620                            transferred: streams.transferred(),
621                            payload,
622                        },
623                        Err(error) => wire_answer(Err(error)),
624                    },
625                    _ => unreachable!("only stream traffic bypasses the phase loan"),
626                }
627            })
628        }
629    }
630
631    pub fn begin(
632        &mut self, command: WireCommand, context: Arc<ExecutionContext>,
633    ) -> Pin<Box<dyn Future<Output = WireAnswer> + Send + 'static>> {
634        let (invocation, phase) = command_identity(&command);
635        let span = tracing::debug_span!(target: "harmos::carrier", "carrier.receive", invocation, phase, outcome = tracing::field::Empty);
636        if command.is_stream_traffic() {
637            return Box::pin(self.traffic(command).instrument(span).in_current_context());
638        }
639        let slot = match &command {
640            WireCommand::Initialize { invocation, .. }
641            | WireCommand::Attempt { invocation, .. }
642            | WireCommand::StreamAttempt { invocation, .. }
643            | WireCommand::Finalize { invocation } => self.prepared.get(invocation).cloned(),
644            WireCommand::Prepare { .. } | WireCommand::PrepareGrpc { .. } => None,
645            WireCommand::StreamSend { .. } | WireCommand::StreamFinish { .. } | WireCommand::StreamReceive { .. } => {
646                unreachable!("stream traffic already dispatched")
647            }
648        };
649        let command = match command {
650            WireCommand::PrepareGrpc {
651                invocation,
652                operation,
653                fingerprint,
654                generation,
655                payload,
656            } => {
657                let result = span.in_scope(|| self.prepare_codec(invocation, &operation, fingerprint, generation, payload, true));
658                return Box::pin(async move { wire_answer(result) }.instrument(span).in_current_context());
659            }
660            WireCommand::Prepare {
661                invocation,
662                operation,
663                fingerprint,
664                generation,
665                payload,
666            } => {
667                let result = span.in_scope(|| self.prepare(invocation, &operation, fingerprint, generation, payload));
668                return Box::pin(async move { wire_answer(result) }.instrument(span).in_current_context());
669            }
670            command => command,
671        };
672        let refused = self.closed || (self.ordinary_closed && slot.as_ref().is_some_and(|slot| !slot.lifecycle));
673        if refused && matches!(command, WireCommand::Initialize { .. } | WireCommand::Attempt { .. } | WireCommand::StreamAttempt { .. }) {
674            return Box::pin(async { wire_answer(Err(ServingError::Closing)) }.instrument(span).in_current_context());
675        }
676        Box::pin(
677            async move {
678                let result = match command {
679                    WireCommand::Initialize { invocation, .. } => match slot {
680                        Some(slot) => slot.bind(invocation, &context).await.map(|()| Vec::new()),
681                        None => Err(ServingError::Missing { invocation }),
682                    },
683                    WireCommand::Attempt { invocation, .. } => match slot {
684                        Some(slot) => slot.attempt(invocation, &context, None).await,
685                        None => Err(ServingError::Missing { invocation }),
686                    },
687                    WireCommand::StreamAttempt { invocation, epoch, .. } => match slot {
688                        Some(slot) => slot.attempt(invocation, &context, Some(epoch)).await,
689                        None => Err(ServingError::Missing { invocation }),
690                    },
691                    WireCommand::StreamSend { .. } | WireCommand::StreamFinish { .. } | WireCommand::StreamReceive { .. } => {
692                        unreachable!("stream traffic already dispatched")
693                    }
694                    WireCommand::Finalize { .. } => match slot {
695                        Some(slot) => slot.finalize().await.map(|()| Vec::new()),
696                        None => Ok(Vec::new()),
697                    },
698                    WireCommand::Prepare { .. } | WireCommand::PrepareGrpc { .. } => {
699                        unreachable!("preparation is synchronous")
700                    }
701                };
702                wire_answer(result)
703            }
704            .instrument(span)
705            .in_current_context(),
706        )
707    }
708
709    pub fn close_ordinary(&mut self) -> Pin<Box<dyn Future<Output = Result<(), ServingError>> + Send + 'static>> {
710        self.ordinary_closed = true;
711        let slots: Vec<_> = self.prepared.values().filter(|slot| !slot.lifecycle).cloned().collect();
712        for slot in &slots {
713            slot.cancel();
714        }
715        Box::pin(async move {
716            for slot in slots {
717                slot.finalize().await?;
718            }
719            Ok(())
720        })
721    }
722
723    pub fn release_ordinary(&mut self) -> Result<impl Send + use<>, ServingError> {
724        if !self.ordinary_closed || self.prepared.values().any(|slot| !slot.lifecycle && !slot.is_finished()) {
725            return Err(ServingError::Unsettled);
726        }
727        // Hand Off Retired Owners So The Caller Can Drop Them Outside Its Lock
728        let retired_slots = self.prepared.extract_if(.., |_, slot| !slot.lifecycle).collect::<Vec<_>>();
729        let retired_handlers = self.handlers.extract_if(.., |_, handler| !handler.lifecycle).collect::<Vec<_>>();
730        let retired_services = std::mem::take(&mut self.services);
731        Ok((retired_slots, retired_handlers, retired_services))
732    }
733
734    pub async fn settle_ordinary(&mut self) -> Result<(), ServingError> {
735        self.close_ordinary().await?;
736        let retired = self.release_ordinary()?;
737        drop(retired);
738        Ok(())
739    }
740
741    pub fn close(&mut self) -> Pin<Box<dyn Future<Output = Result<(), ServingError>> + Send + 'static>> {
742        self.closed = true;
743        let slots: Vec<_> = self.prepared.values().cloned().collect();
744        for slot in &slots {
745            slot.cancel();
746        }
747        Box::pin(async move {
748            for slot in slots {
749                slot.finalize().await?;
750            }
751            Ok(())
752        })
753    }
754
755    pub fn release(&mut self) -> Result<impl Send + use<>, ServingError> {
756        if !self.closed || self.prepared.values().any(|slot| !slot.is_finished()) {
757            return Err(ServingError::Unsettled);
758        }
759        Ok((std::mem::take(&mut self.prepared), std::mem::take(&mut self.handlers), std::mem::take(&mut self.services)))
760    }
761
762    pub async fn settle(&mut self) -> Result<(), ServingError> {
763        self.close().await?;
764        let retired = self.release()?;
765        drop(retired);
766        Ok(())
767    }
768
769    pub fn is_settled(&self) -> bool {
770        self.closed && self.prepared.values().all(|slot| slot.is_finished())
771    }
772
773    pub fn is_closed(&self) -> bool {
774        self.closed
775    }
776
777    #[tracing::instrument(target = "harmos::carrier", name = "carrier.answer", level = "debug", skip_all, fields(invocation = command_identity(&command).0, phase = command_identity(&command).1))]
778    pub async fn answer(&mut self, command: WireCommand, context: &ExecutionContext) -> WireAnswer {
779        if command.is_stream_traffic() {
780            return self.traffic(command).await;
781        }
782        if let WireCommand::StreamAttempt { invocation, epoch, .. } = command {
783            if self.closed || (self.ordinary_closed && self.prepared.get(&invocation).is_some_and(|slot| !slot.lifecycle)) {
784                return wire_answer(Err(ServingError::Closing));
785            }
786            let Some(slot) = self.prepared.get(&invocation) else {
787                return wire_answer(Err(ServingError::Missing { invocation }));
788            };
789            return wire_answer(slot.attempt(invocation, context, Some(epoch)).await);
790        }
791        let result = match command {
792            WireCommand::PrepareGrpc {
793                invocation,
794                operation,
795                fingerprint,
796                generation,
797                payload,
798            } => self.prepare_codec(invocation, &operation, fingerprint, generation, payload, true),
799            WireCommand::Prepare {
800                invocation,
801                operation,
802                fingerprint,
803                generation,
804                payload,
805            } => self.prepare(invocation, &operation, fingerprint, generation, payload),
806            WireCommand::Initialize { invocation, .. } => self.bind(invocation, context).await.map(|()| Vec::new()),
807            WireCommand::Attempt { invocation, .. } => self.attempt(invocation, context).await,
808            WireCommand::StreamAttempt { .. }
809            | WireCommand::StreamSend { .. }
810            | WireCommand::StreamFinish { .. }
811            | WireCommand::StreamReceive { .. } => {
812                unreachable!("stream command already dispatched")
813            }
814            WireCommand::Finalize { invocation } => self.finalize(invocation).await.map(|()| Vec::new()),
815        };
816        wire_answer(result)
817    }
818}
819
820impl Slot {
821    fn cancel(&self) {
822        let waiters = {
823            let mut state = self.state.lock().expect("invocation state lock");
824            state.cancelled = true;
825            std::mem::take(&mut state.waiters)
826        };
827        #[cfg(feature = "streaming")]
828        if let Some(streams) = &self.streams {
829            streams.close();
830        }
831        for waiter in waiters {
832            if let Some(waiter) = waiter.upgrade() {
833                let wake = waiter.lock().expect("invocation waiter lock").take();
834                if let Some(wake) = wake {
835                    wake.wake();
836                }
837            }
838        }
839    }
840
841    async fn active<T>(&self, future: impl Future<Output = Result<T, ServingError>>) -> Result<T, ServingError> {
842        let mut future = std::pin::pin!(future);
843        let waiter = Arc::new(Mutex::new(None));
844        std::future::poll_fn(|context| {
845            {
846                let mut state = self.state.lock().expect("invocation state lock");
847                if state.cancelled {
848                    return Poll::Ready(Err(ServingError::Closing));
849                }
850                *waiter.lock().expect("invocation waiter lock") = Some(context.waker().clone());
851                state.waiters.retain(|entry| entry.strong_count() != 0);
852                if !state.waiters.iter().any(|entry| entry.ptr_eq(&Arc::downgrade(&waiter))) {
853                    state.waiters.push(Arc::downgrade(&waiter));
854                }
855            }
856            future.as_mut().poll(context)
857        })
858        .await
859    }
860
861    fn is_finished(&self) -> bool {
862        self.state.lock().expect("invocation state lock").finished
863    }
864
865    async fn borrow(self: &Arc<Self>) -> Option<Loan> {
866        let waiter = Arc::new(Mutex::new(None));
867        std::future::poll_fn(|context| {
868            let mut state = self.state.lock().expect("invocation state lock");
869            if state.finished {
870                return Poll::Ready(None);
871            }
872            if let Some(prepared) = state.prepared.take() {
873                return Poll::Ready(Some(Loan {
874                    slot: Arc::clone(self),
875                    prepared: Some(prepared),
876                    finished: false,
877                }));
878            }
879            *waiter.lock().expect("invocation waiter lock") = Some(context.waker().clone());
880            state.waiters.retain(|entry| entry.strong_count() != 0);
881            if !state.waiters.iter().any(|entry| entry.ptr_eq(&Arc::downgrade(&waiter))) {
882                state.waiters.push(Arc::downgrade(&waiter));
883            }
884            Poll::Pending
885        })
886        .await
887    }
888}
889
890impl Slot {
891    #[tracing::instrument(target = "harmos::streams", name = "streams.initialize", level = "trace", skip_all, fields(invocation))]
892    async fn bind(self: &Arc<Self>, invocation: u64, context: &ExecutionContext) -> Result<(), ServingError> {
893        let mut loan = self.borrow().await.ok_or(ServingError::Missing { invocation })?;
894        self.active(loan.prepared.as_mut().expect("loaned invocation state").bind(context)).await
895    }
896
897    #[tracing::instrument(target = "harmos::streams", name = "streams.attempt", level = "trace", skip_all, fields(invocation))]
898    async fn attempt(self: &Arc<Self>, invocation: u64, context: &ExecutionContext, epoch: Option<u64>) -> Result<Vec<u8>, ServingError> {
899        let mut loan = self.borrow().await.ok_or(ServingError::Missing { invocation })?;
900        #[cfg(feature = "streaming")]
901        let attempt = match (&self.streams, epoch) {
902            (Some(streams), Some(epoch)) => Some(streams.start(epoch)?),
903            (None, None) => None,
904            _ => return Err(ServingError::StreamUnsupported),
905        };
906        #[cfg(not(feature = "streaming"))]
907        if epoch.is_some() {
908            return Err(ServingError::StreamUnsupported);
909        }
910        let result = self.active(loan.prepared.as_mut().expect("loaned invocation state").attempt(context)).await;
911        #[cfg(feature = "streaming")]
912        if let Some(attempt) = attempt {
913            attempt.end();
914        }
915        result
916    }
917
918    #[tracing::instrument(target = "harmos::carrier", name = "carrier.finalize", level = "debug", skip_all)]
919    async fn finalize(self: &Arc<Self>) -> Result<(), ServingError> {
920        #[cfg(feature = "streaming")]
921        if let Some(streams) = &self.streams {
922            streams.close();
923        }
924        let Some(mut loan) = self.borrow().await else {
925            return Ok(());
926        };
927        loan.prepared.as_mut().expect("loaned invocation state").finalize().await?;
928        // Drop Physical State Before Releasing Its Capacity
929        loan.finished = true;
930        let prepared = loan.prepared.take();
931        drop(prepared);
932        Ok(())
933    }
934}
935
936impl Drop for Loan {
937    fn drop(&mut self) {
938        let waiters = {
939            let mut state = self.slot.state.lock().expect("invocation state lock");
940            state.prepared = self.prepared.take();
941            state.finished = self.finished;
942            std::mem::take(&mut state.waiters)
943        };
944        for waiter in waiters {
945            if let Some(waiter) = waiter.upgrade() {
946                let wake = waiter.lock().expect("invocation waiter lock").take();
947                if let Some(wake) = wake {
948                    wake.wake();
949                }
950            }
951        }
952    }
953}
954
955impl WireCommand {
956    pub const LIMIT: usize = codec::LIMIT;
957    fn is_stream_traffic(&self) -> bool {
958        matches!(self, Self::StreamSend { .. } | Self::StreamFinish { .. } | Self::StreamReceive { .. })
959    }
960}
961
962impl ServingError {
963    pub fn classification(&self) -> FailureKind {
964        match self {
965            Self::Handler(failure) => failure.code(),
966            Self::Panicked => FailureKind::Ambiguous,
967            Self::Codec(_) | Self::Declaration(_) | Self::Lifecycle(_) | Self::Contract(_) | Self::Catalog | Self::Streaming { .. } => {
968                FailureKind::Invalid
969            }
970            _ => FailureKind::Permanent,
971        }
972    }
973}
974
975/* === Public Functions === */
976
977// A Prepare answer is empty when the request needs no grant, else the grant as JSON.
978pub fn encode_prepared_grant(grant: Option<&crate::plugin::Grant>) -> Vec<u8> {
979    grant.map_or_else(Vec::new, |grant| serde_json::to_vec(grant).expect("a grant serializes to JSON"))
980}
981
982pub fn decode_prepared_grant(payload: &[u8]) -> Result<Option<crate::plugin::Grant>, serde_json::Error> {
983    if payload.is_empty() {
984        return Ok(None);
985    }
986    serde_json::from_slice(payload).map(Some)
987}
988
989/* === Private Functions === */
990
991fn command_identity(command: &WireCommand) -> (u64, &'static str) {
992    match command {
993        WireCommand::Prepare { invocation, .. } => (*invocation, "prepare"),
994        WireCommand::PrepareGrpc { invocation, .. } => (*invocation, "prepare_grpc"),
995        WireCommand::Initialize { invocation, .. } => (*invocation, "initialize"),
996        WireCommand::Attempt { invocation, .. } => (*invocation, "attempt"),
997        WireCommand::Finalize { invocation, .. } => (*invocation, "finalize"),
998        WireCommand::StreamAttempt { invocation, .. } => (*invocation, "stream_attempt"),
999        WireCommand::StreamSend { invocation, .. } => (*invocation, "stream_send"),
1000        WireCommand::StreamFinish { invocation, .. } => (*invocation, "stream_finish"),
1001        WireCommand::StreamReceive { invocation, .. } => (*invocation, "stream_receive"),
1002    }
1003}
1004
1005fn wire_answer(result: Result<Vec<u8>, ServingError>) -> WireAnswer {
1006    tracing::Span::current().record("outcome", if result.is_ok() { "ready" } else { "failed" });
1007    match result {
1008        Ok(payload) => WireAnswer::Ready { payload },
1009        Err(ServingError::Handler(failure)) => WireAnswer::Failed { failure },
1010        Err(error) => WireAnswer::Failed {
1011            failure: crate::Failure::originate(error.classification(), &error, crate::failure::Origin::Plugin),
1012        },
1013    }
1014}
1015
1016async fn guarded<T>(future: impl Future<Output = Result<T, ServingError>>) -> Result<T, ServingError> {
1017    let mut future = std::pin::pin!(future);
1018    std::future::poll_fn(|context| match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| future.as_mut().poll(context))) {
1019        Ok(result) => result,
1020        Err(_) => std::task::Poll::Ready(Err(ServingError::Panicked)),
1021    })
1022    .await
1023}
1024
1025/* === Tests === */
1026
1027#[cfg(test)]
1028mod tests {
1029    use super::*;
1030
1031    #[test]
1032    fn withdrawal_cancels_a_pending_active_future() {
1033        let slot = Slot {
1034            operation: "host.read".to_owned(),
1035            lifecycle: false,
1036            resident: false,
1037            #[cfg(feature = "streaming")]
1038            streams: None,
1039            state: Mutex::new(SlotState {
1040                prepared: None,
1041                finished: false,
1042                cancelled: false,
1043                waiters: Vec::new(),
1044            }),
1045        };
1046        let mut active = Box::pin(slot.active(std::future::pending::<Result<(), ServingError>>()));
1047        let mut context = std::task::Context::from_waker(Waker::noop());
1048        assert!(active.as_mut().poll(&mut context).is_pending());
1049        slot.cancel();
1050        assert!(matches!(active.as_mut().poll(&mut context), Poll::Ready(Err(ServingError::Closing))));
1051    }
1052}