1use std::{
2 any::Any,
3 collections::BTreeMap,
4 fmt,
5 future::Future,
6 marker::PhantomData,
7 pin::Pin,
8 rc::Rc,
9 sync::{
10 Arc,
11 atomic::{AtomicBool, Ordering},
12 },
13 task::{Context, Poll},
14 time::Instant,
15};
16
17use super::{LaneRoute, LaneTask};
18use futures::{future::LocalBoxFuture, task::AtomicWaker};
19use lenso_app_plan::ResolvedAppPlan;
20use lenso_kernel::{
21 CancellationToken, InvocationContext, NativeRequestEndpoint, NativeRequestFuture,
22 RequestCapability, RuntimeFailure, TypedNativeRequestEndpoint,
23};
24
25trait RequestTransferFactory: fmt::Debug + Send + Sync {
26 fn endpoint(&self, provider_lane: LaneRoute, epoch: Instant) -> Rc<dyn NativeRequestEndpoint>;
27}
28
29struct TypedRequestTransferFactory<C: RequestCapability> {
30 operations: &'static [&'static str],
31 capability: PhantomData<fn() -> C>,
32}
33
34impl<C: RequestCapability> fmt::Debug for TypedRequestTransferFactory<C> {
35 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
36 formatter
37 .debug_struct("TypedRequestTransferFactory")
38 .field("capability", &C::ID)
39 .finish_non_exhaustive()
40 }
41}
42
43impl<C> RequestTransferFactory for TypedRequestTransferFactory<C>
44where
45 C: RequestCapability,
46 C::Request: Send,
47 C::Response: Send,
48 C::DomainError: Send,
49{
50 fn endpoint(&self, provider_lane: LaneRoute, epoch: Instant) -> Rc<dyn NativeRequestEndpoint> {
51 let typed_provider_lane = provider_lane.clone();
52 let operations = self.operations;
53 Rc::new(CrossLaneRequestEndpoint::<C> {
54 operations: self.operations,
55 typed: TypedNativeRequestEndpoint::new(move |operation, request, context| {
56 let Some(operation) = operations
57 .iter()
58 .copied()
59 .find(|candidate| *candidate == operation)
60 else {
61 return Box::pin(futures::future::ready(Err(
62 RuntimeFailure::UnknownOperation {
63 capability: C::ID,
64 operation: operation.to_owned(),
65 },
66 )));
67 };
68 invoke_cross_lane::<C>(
69 typed_provider_lane.clone(),
70 epoch,
71 operation,
72 request,
73 context,
74 )
75 }),
76 })
77 }
78}
79
80#[derive(Clone, Debug, Default)]
82pub struct CrossLaneRequestCatalog {
83 factories: BTreeMap<&'static str, Arc<dyn RequestTransferFactory>>,
84}
85
86impl CrossLaneRequestCatalog {
87 pub fn new() -> Self {
89 Self::default()
90 }
91
92 #[must_use]
94 pub fn with_request<C>(mut self, operations: &'static [&'static str]) -> Self
95 where
96 C: RequestCapability,
97 C::Request: Send,
98 C::Response: Send,
99 C::DomainError: Send,
100 {
101 self.factories.insert(
102 C::ID,
103 Arc::new(TypedRequestTransferFactory::<C> {
104 operations,
105 capability: PhantomData,
106 }),
107 );
108 self
109 }
110
111 pub(super) fn contains(&self, capability_id: &str) -> bool {
112 self.factories.contains_key(capability_id)
113 }
114
115 pub(super) fn validate_plan(
116 &self,
117 plan: &ResolvedAppPlan,
118 ) -> Result<(), super::ReplicatedRunnerError> {
119 for binding in plan.capability_bindings() {
120 let consumer = plan
121 .module_instance(binding.consumer_instance())
122 .expect("validated binding consumer should exist");
123 let provider = plan
124 .module_instance(binding.provider_instance())
125 .expect("validated binding provider should exist");
126 let endpoint = provider
127 .provided_capabilities()
128 .iter()
129 .find(|endpoint| endpoint.capability_id() == binding.capability_id())
130 .expect("validated provider endpoint should exist");
131 if consumer.execution_lane() != provider.execution_lane()
132 && !endpoint.request_operations().is_empty()
133 && !self.contains(binding.capability_id())
134 {
135 return Err(
136 super::ReplicatedRunnerError::MissingCrossLaneRequestTransfer {
137 capability: binding.capability_id().to_owned(),
138 },
139 );
140 }
141 }
142 Ok(())
143 }
144
145 pub(super) fn endpoint(
146 &self,
147 capability_id: &str,
148 provider_lane: LaneRoute,
149 epoch: Instant,
150 ) -> Option<Rc<dyn NativeRequestEndpoint>> {
151 self.factories
152 .get(capability_id)
153 .map(|factory| factory.endpoint(provider_lane, epoch))
154 }
155}
156
157struct CrossLaneRequestEndpoint<C: RequestCapability> {
158 operations: &'static [&'static str],
159 typed: TypedNativeRequestEndpoint<C>,
160}
161
162impl<C: RequestCapability> fmt::Debug for CrossLaneRequestEndpoint<C> {
163 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
164 formatter
165 .debug_struct("CrossLaneRequestEndpoint")
166 .field("capability", &C::ID)
167 .finish_non_exhaustive()
168 }
169}
170
171impl<C> NativeRequestEndpoint for CrossLaneRequestEndpoint<C>
172where
173 C: RequestCapability,
174 C::Request: Send,
175 C::Response: Send,
176 C::DomainError: Send,
177{
178 fn capability_id(&self) -> &'static str {
179 C::ID
180 }
181
182 fn descriptor_version(&self) -> &'static str {
183 C::DESCRIPTOR_VERSION
184 }
185
186 fn operations(&self) -> &'static [&'static str] {
187 self.operations
188 }
189
190 fn typed_endpoint(&self) -> Option<&dyn Any> {
191 Some(&self.typed)
192 }
193
194 fn invoke(
195 &self,
196 operation: &str,
197 request: Box<dyn Any>,
198 context: InvocationContext,
199 ) -> LocalBoxFuture<'static, Result<Result<Box<dyn Any>, Box<dyn Any>>, RuntimeFailure>> {
200 let Ok(request) = request.downcast::<C::Request>() else {
201 return Box::pin(futures::future::ready(Err(
202 RuntimeFailure::ProtocolViolation { capability: C::ID },
203 )));
204 };
205 let invocation = self.typed.invoke(operation, *request, context);
206 Box::pin(async move {
207 let result = invocation.await?;
208 Ok(result
209 .map(|response| Box::new(response) as Box<dyn Any>)
210 .map_err(|error| Box::new(error) as Box<dyn Any>))
211 })
212 }
213}
214
215fn invoke_cross_lane<C>(
216 provider_lane: LaneRoute,
217 epoch: Instant,
218 operation: &'static str,
219 request: C::Request,
220 context: InvocationContext,
221) -> NativeRequestFuture<C>
222where
223 C: RequestCapability,
224 C::Request: Send,
225 C::Response: Send,
226 C::DomainError: Send,
227{
228 Box::pin(async move {
229 let provider_lane = provider_lane.upgrade().ok_or_else(lane_unavailable::<C>)?;
230 let caller_instance = context
231 .caller_instance()
232 .ok_or_else(|| RuntimeFailure::InvalidResolvedPlan {
233 detail: format!("cross-lane invocation of `{}` has no planned caller", C::ID),
234 })?
235 .to_owned();
236 let cancellation = context.cancellation();
237 let deadline = context.deadline();
238 let request_id = context.request_id();
239 let (transferred, cancellation_signal) = TransferredInvocationContext::capture(&context);
240 let (completed, completion) = futures::channel::oneshot::channel();
241 let command: LaneTask = Box::new(move |lane| {
242 tokio::task::spawn_local(async move {
243 let local_cancellation = CancellationToken::new();
244 let (context, transferred_cancellation) =
245 transferred.restore(local_cancellation.clone());
246 if transferred_cancellation.is_cancelled() {
247 local_cancellation.cancel();
248 }
249 let handle = match lane.request_handle::<C>(&caller_instance) {
250 Ok(handle) => handle,
251 Err(error) => {
252 let _ = completed.send(Err(error));
253 return;
254 }
255 };
256 let invocation = handle.invoke_with_context(operation, context, request);
257 tokio::pin!(invocation);
258 let result = if local_cancellation.is_cancelled() {
259 invocation.await
260 } else {
261 tokio::select! {
262 result = &mut invocation => result,
263 () = transferred_cancellation.cancelled() => {
264 local_cancellation.cancel();
265 invocation.await
266 }
267 }
268 };
269 let _ = completed.send(result);
270 });
271 });
272
273 let send = provider_lane.send(command);
274 tokio::pin!(send);
275 let cancelled = cancellation.cancelled();
276 tokio::pin!(cancelled);
277 if let Some(deadline) = deadline {
278 let sleep = tokio::time::sleep_until((epoch + deadline).into());
279 tokio::pin!(sleep);
280 tokio::select! {
281 result = &mut send => result.map_err(|_| lane_unavailable::<C>())?,
282 () = &mut cancelled => {
283 cancellation_signal.cancel();
284 return Err(RuntimeFailure::Cancelled { request_id });
285 }
286 () = &mut sleep => {
287 cancellation_signal.cancel();
288 return Err(RuntimeFailure::DeadlineExceeded { request_id });
289 }
290 }
291 tokio::select! {
292 biased;
293 result = completion => result.map_err(|_| lane_unavailable::<C>())?,
294 () = &mut cancelled => {
295 cancellation_signal.cancel();
296 Err(RuntimeFailure::Cancelled { request_id })
297 }
298 () = &mut sleep => {
299 cancellation_signal.cancel();
300 Err(RuntimeFailure::DeadlineExceeded { request_id })
301 }
302 }
303 } else {
304 tokio::select! {
305 result = &mut send => result.map_err(|_| lane_unavailable::<C>())?,
306 () = &mut cancelled => {
307 cancellation_signal.cancel();
308 return Err(RuntimeFailure::Cancelled { request_id });
309 }
310 }
311 tokio::select! {
312 biased;
313 result = completion => result.map_err(|_| lane_unavailable::<C>())?,
314 () = &mut cancelled => {
315 cancellation_signal.cancel();
316 Err(RuntimeFailure::Cancelled { request_id })
317 }
318 }
319 }
320 })
321}
322
323fn lane_unavailable<C: RequestCapability>() -> RuntimeFailure {
324 RuntimeFailure::Internal {
325 detail: format!("provider lane for `{}` is unavailable", C::ID),
326 }
327}
328
329#[derive(Debug)]
330struct TransferredInvocationContext {
331 request_id: u64,
332 deadline: Option<std::time::Duration>,
333 cancellation: Arc<TransferredCancellation>,
334 extensions: Vec<lenso_kernel::InvocationExtension>,
335 sealed_extensions: Vec<lenso_kernel::SealedInvocationExtension>,
336}
337
338impl TransferredInvocationContext {
339 fn capture(context: &InvocationContext) -> (Self, Arc<TransferredCancellation>) {
340 let cancellation = Arc::new(TransferredCancellation::new(context.is_cancelled()));
341 (
342 Self {
343 request_id: context.request_id(),
344 deadline: context.deadline(),
345 cancellation: Arc::clone(&cancellation),
346 extensions: context.extensions().cloned().collect(),
347 sealed_extensions: context.sealed_extensions().cloned().collect(),
348 },
349 cancellation,
350 )
351 }
352
353 fn restore(
354 self,
355 cancellation: CancellationToken,
356 ) -> (InvocationContext, Arc<TransferredCancellation>) {
357 let mut context = InvocationContext::new(self.request_id, self.deadline, cancellation);
358 for extension in self.extensions {
359 context = context
360 .with_extension(extension.key(), extension.value().to_vec())
361 .expect("captured ordinary Invocation Context extension remains valid");
362 }
363 for extension in self.sealed_extensions {
364 context = context
365 .with_sealed_extension(extension)
366 .expect("captured sealed Invocation Context extension remains valid");
367 }
368 (context, self.cancellation)
369 }
370}
371
372#[derive(Debug)]
373struct TransferredCancellation {
374 cancelled: AtomicBool,
376 waker: AtomicWaker,
377}
378
379impl TransferredCancellation {
380 fn new(cancelled: bool) -> Self {
381 Self {
382 cancelled: AtomicBool::new(cancelled),
383 waker: AtomicWaker::new(),
384 }
385 }
386
387 fn is_cancelled(&self) -> bool {
388 self.cancelled.load(Ordering::Acquire)
389 }
390
391 fn cancel(&self) {
392 if !self.cancelled.swap(true, Ordering::AcqRel) {
393 self.waker.wake();
394 }
395 }
396
397 fn cancelled(&self) -> TransferredCancellationFuture<'_> {
398 TransferredCancellationFuture { cancellation: self }
399 }
400}
401
402struct TransferredCancellationFuture<'a> {
403 cancellation: &'a TransferredCancellation,
404}
405
406impl Future for TransferredCancellationFuture<'_> {
407 type Output = ();
408
409 fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
410 if self.cancellation.is_cancelled() {
411 return Poll::Ready(());
412 }
413 self.cancellation.waker.register(context.waker());
414 if self.cancellation.is_cancelled() {
415 Poll::Ready(())
416 } else {
417 Poll::Pending
418 }
419 }
420}
421
422#[cfg(test)]
423mod tests {
424 use std::sync::Arc;
425
426 use super::TransferredCancellation;
427
428 #[tokio::test(flavor = "current_thread")]
429 async fn transferred_cancellation_observes_an_initial_signal() {
430 let cancellation = TransferredCancellation::new(true);
431
432 cancellation.cancelled().await;
433
434 assert!(cancellation.is_cancelled());
435 }
436
437 #[tokio::test(flavor = "current_thread")]
438 async fn transferred_cancellation_wakes_the_provider_waiter() {
439 let cancellation = Arc::new(TransferredCancellation::new(false));
440 let canceller = Arc::clone(&cancellation);
441
442 tokio::join!(cancellation.cancelled(), async move {
443 tokio::task::yield_now().await;
444 canceller.cancel();
445 });
446
447 assert!(cancellation.is_cancelled());
448 }
449}