use std::sync::Arc;
use async_trait::async_trait;
use aion_core::{ActivityId, RunId, WorkflowId};
use aion_proto::ProtoActivityTask;
use super::delivery_intent::SharedDeliveryIntent;
use super::intervention::{AttemptKey, AttemptOwnerIndex};
use super::liminal_transport::{AttemptOwnerGuard, DispatchRequest, LiminalCompletionSource};
use super::registry::{WorkerDelivery, WorkerHandle};
use super::task_delivery::{LivenessTracking, TaskDelivery, WorkerTaskDelivery};
pub struct LiminalTaskDelivery {
completion: Arc<LiminalCompletionSource>,
attempt_owners: Option<AttemptOwnerIndex>,
}
impl std::fmt::Debug for LiminalTaskDelivery {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("LiminalTaskDelivery")
.field("attempt_owners", &self.attempt_owners.is_some())
.finish_non_exhaustive()
}
}
impl LiminalTaskDelivery {
#[must_use]
pub fn new(completion: Arc<LiminalCompletionSource>) -> Self {
Self {
completion,
attempt_owners: None,
}
}
#[must_use]
pub fn with_attempt_owners(mut self, attempt_owners: AttemptOwnerIndex) -> Self {
self.attempt_owners = Some(attempt_owners);
self
}
}
struct Resolved {
workflow_id: WorkflowId,
run_id: RunId,
activity_id: ActivityId,
attempt: u32,
}
impl Resolved {
fn from_task(task: &ProtoActivityTask) -> Result<Self, &'static str> {
let workflow_id = task
.workflow_id
.clone()
.ok_or("task carries no workflow id")?
.try_into()
.map_err(|_| "task carries a malformed workflow id")?;
let run_id: RunId = task
.run_id
.clone()
.ok_or("activity run id is missing; refusing unfenced external effect")?
.try_into()
.map_err(|_| "task carries a malformed run id")?;
let activity_id: ActivityId = task
.activity_id
.ok_or("task carries no activity id")?
.into();
Ok(Self {
workflow_id,
run_id,
activity_id,
attempt: task.attempt,
})
}
fn attempt_key(&self) -> AttemptKey {
AttemptKey::new(
self.workflow_id.clone(),
self.run_id.clone(),
self.activity_id.clone(),
self.attempt,
)
}
fn bind_owner(
&self,
owners: Option<&AttemptOwnerIndex>,
worker: super::registry::WorkerId,
) -> Option<AttemptOwnerGuard> {
owners.map(|owners| AttemptOwnerGuard::bind(owners.clone(), self.attempt_key(), worker))
}
fn ordinal(&self) -> u64 {
self.activity_id.sequence_position()
}
}
fn request_for_task(task: &ProtoActivityTask, resolved: &Resolved) -> DispatchRequest {
DispatchRequest {
activity_type: task.activity_type.clone(),
workflow_id: resolved.workflow_id.clone(),
ordinal: resolved.ordinal(),
run_id: Some(resolved.run_id.clone()),
completion_token: task.completion_token.clone(),
idempotency_key: task.idempotency_key.clone(),
input: task
.input
.as_ref()
.map(|payload| payload.bytes.clone())
.unwrap_or_default(),
attempt: resolved.attempt,
labels: task
.labels
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect(),
heartbeat_window_ms: LivenessTracking::NotTrackedPerTask.heartbeat_window_ms(),
}
}
#[async_trait]
impl WorkerTaskDelivery for LiminalTaskDelivery {
async fn deliver(
&self,
worker: &WorkerHandle,
task: &ProtoActivityTask,
intent: &SharedDeliveryIntent,
) -> TaskDelivery {
let resolved = match Resolved::from_task(task) {
Ok(resolved) => resolved,
Err(reason) => return TaskDelivery::failed(reason),
};
let delivery = match worker.delivery() {
WorkerDelivery::Liminal(delivery) => delivery.clone(),
WorkerDelivery::Grpc(_) => {
return TaskDelivery::failed(
"selected worker is not delivered over liminal; the liminal transport cannot \
reach it",
);
}
};
let _owner_guard = resolved.bind_owner(self.attempt_owners.as_ref(), worker.id());
let request = request_for_task(task, &resolved);
let waiting_intent = Arc::clone(intent);
let dispatched = tokio::task::spawn_blocking(move || {
delivery.dispatch_held(&request, || waiting_intent.still_wanted())
})
.await;
let response = match dispatched {
Ok(Ok(Some(response))) => response,
Ok(Ok(None)) => {
return TaskDelivery::failed("delivery wait abandoned before worker reply");
}
Ok(Err(error)) => {
return TaskDelivery::failed(format!("liminal dispatch failed: {error}"));
}
Err(error) => {
return TaskDelivery::failed(format!("dispatch task join failed: {error}"));
}
};
if let Err(error) = self.completion.deliver(&response) {
return TaskDelivery::failed(format!(
"worker replied but the completion could not be recorded: {error}"
));
}
TaskDelivery::Delivered
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use aion_core::{ActivityId, InterventionCapabilities, RunId, WorkflowId};
use aion_proto::{ProtoActivityId, ProtoActivityTask, ProtoWorkflowId};
use uuid::Uuid;
use crate::error::ServerError;
use crate::worker::bridge::OutboxDeliveryCallback;
use crate::worker::delivery_intent::{AlwaysWanted, SharedDeliveryIntent};
use crate::worker::intervention::AttemptOwnerIndex;
use crate::worker::liminal_transport::LiminalCompletionSource;
use crate::worker::registry::{ConnectedWorkerRegistry, WorkerDelivery};
use crate::worker::task_delivery::{TaskDelivery, WorkerTaskDelivery};
use super::{LiminalTaskDelivery, Resolved};
struct NoopCallback;
impl OutboxDeliveryCallback for NoopCallback {
fn deliver_completion(
&self,
_workflow_id: &WorkflowId,
_activity_id: &ActivityId,
_run_id: Option<&RunId>,
_result: String,
) -> Result<bool, ServerError> {
Ok(false)
}
fn deliver_failure(
&self,
_workflow_id: &WorkflowId,
_activity_id: &ActivityId,
_run_id: Option<&RunId>,
_reason: String,
) -> Result<bool, ServerError> {
Ok(false)
}
}
const WORKFLOW: u128 = 0x51;
fn task_without_a_run() -> ProtoActivityTask {
ProtoActivityTask {
workflow_id: Some(ProtoWorkflowId::from(WorkflowId::new(Uuid::from_u128(
WORKFLOW,
)))),
activity_id: Some(ProtoActivityId::from(ActivityId::from_sequence_position(3))),
activity_type: String::from("agent"),
input: None,
attempt: 1,
labels: std::collections::HashMap::new(),
run_id: None,
completion_token: String::from("token"),
idempotency_key: String::from("key"),
}
}
fn liminal_delivery(owners: &AttemptOwnerIndex) -> LiminalTaskDelivery {
LiminalTaskDelivery::new(Arc::new(LiminalCompletionSource::new(Arc::new(
NoopCallback,
))))
.with_attempt_owners(owners.clone())
}
#[tokio::test]
async fn run_resolution_precedes_attempt_owner_binding()
-> Result<(), Box<dyn std::error::Error>> {
let owners = AttemptOwnerIndex::new();
let delivery = liminal_delivery(&owners);
let registry = ConnectedWorkerRegistry::default();
let (sender, _receiver) = tokio::sync::mpsc::channel(1);
let types = [String::from("agent")];
let registration = registry.register_delivery_with_capabilities(
[String::from("default")],
String::from("default"),
None,
types.iter(),
WorkerDelivery::Grpc(sender),
InterventionCapabilities::none(),
)?;
let worker_id = registration
.worker_id()
.ok_or("a registration must assign a worker id")?;
let worker = registry
.worker_by_id(worker_id)?
.ok_or("the worker just registered must be readable")?;
let intent: SharedDeliveryIntent = Arc::new(AlwaysWanted);
let outcome = delivery
.deliver(&worker, &task_without_a_run(), &intent)
.await;
match outcome {
TaskDelivery::Delivered => {
return Err("a task with no run must never be delivered".into());
}
TaskDelivery::Undeliverable(undeliverable) => {
assert!(
undeliverable.reason().contains("run id is missing"),
"a run-less task must be refused BY ITS MISSING RUN, not by the transport; \
got: {}",
undeliverable.reason()
);
assert!(
!undeliverable.deregisters_worker(),
"a malformed task is not evidence that the worker is gone"
);
}
}
let bound = owners.attempts_for_workflow(&WorkflowId::new(Uuid::from_u128(WORKFLOW)));
assert!(
bound.is_empty(),
"the attempt-owner index must be untouched when the run refused; a binding here \
means the bind was lifted above the run resolution, and an intervention could \
resolve the wrong generation's worker. Found: {bound:?}"
);
Ok(())
}
#[test]
fn identity_resolution_refuses_a_task_with_no_run() -> Result<(), Box<dyn std::error::Error>> {
let Err(refusal) = Resolved::from_task(&task_without_a_run()) else {
return Err("a task with no run must not resolve".into());
};
assert!(
refusal.contains("run id is missing"),
"the refusal must name the run so an operator is sent to the right remedy: {refusal}"
);
Ok(())
}
}