Skip to main content

alien_commands/server/
mod.rs

1//! Command Server Implementation
2//!
3//! The Command server implements the command lifecycle:
4//! - CommandRegistry is the SOURCE OF TRUTH for all metadata (state, timestamps, etc.)
5//! - KV stores ONLY operational data (params/response blobs, indices, leases)
6
7use std::sync::Arc;
8use std::time::Duration;
9
10use alien_bindings::presigned::PresignedRequest;
11use alien_bindings::providers::kv::validate_key;
12use alien_bindings::traits::{Kv, PutCondition, PutOptions, Storage};
13use alien_error::{AlienError, Context, ContextError, IntoAlienError};
14use chrono::{DateTime, Utc};
15use hex;
16use hmac::{Hmac, Mac};
17use serde::{Deserialize, Serialize};
18use sha2::{Digest, Sha256};
19use tracing::{debug, info, warn};
20use uuid::Uuid;
21
22use base64::{engine::general_purpose, Engine as _};
23use bytes::Bytes;
24use object_store::path::Path as StoragePath;
25
26use crate::error::{ErrorData, Result};
27use crate::types::*;
28use crate::INLINE_MAX_BYTES;
29
30type HmacSha256 = Hmac<Sha256>;
31
32/// Max serialized KV value size. Conservative threshold below the hard 24KB
33/// boundary (Azure Table Storage) to account for JSON wrapping overhead.
34const KV_VALUE_THRESHOLD: usize = 20_000;
35
36fn is_definite_dispatch_rejection(error: &crate::error::Error) -> bool {
37    matches!(
38        error.error.as_ref(),
39        Some(ErrorData::TransportDispatchRejected { .. })
40    )
41}
42
43pub mod axum_handlers;
44pub mod command_registry;
45pub mod storage;
46
47pub use crate::dispatchers::{CommandDispatcher, NullCommandDispatcher};
48pub use axum_handlers::{
49    create_axum_router, CommandPayloadResponse, HasCommandServer, StorePayloadRequest,
50};
51pub use command_registry::{
52    delivery_mode_for, select_command_target, validate_command_name, validate_command_target_id,
53    CommandAccessContext, CommandEnvelopeData, CommandMetadata, CommandRegistry, CommandStatus,
54    InMemoryCommandRegistry, ResolvedCommandTarget,
55};
56
57// =============================================================================
58// KV Data Structures (Operational Data Only)
59// =============================================================================
60
61/// Params stored in KV (just the blob)
62#[derive(Debug, Clone, Serialize, Deserialize)]
63struct CommandParamsData {
64    pub params: BodySpec,
65}
66
67/// Response stored in KV (just the blob)
68#[derive(Debug, Clone, Serialize, Deserialize)]
69struct CommandResponseData {
70    pub response: CommandResponse,
71}
72
73/// Lease record with TTL
74#[derive(Debug, Clone, Serialize, Deserialize)]
75struct LeaseData {
76    pub lease_id: String,
77    pub acquired_at: DateTime<Utc>,
78    pub expires_at: DateTime<Utc>,
79    pub owner: String,
80    /// Set when a response claims the lease. A claimed lease is not handed to
81    /// another holder before it expires or is deleted.
82    #[serde(default)]
83    pub completing: bool,
84}
85
86/// Which lease a response is submitted under.
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub enum ExpectedLease {
89    /// The response comes from the holder of this lease, and the caller proved
90    /// the lease id some other way (the signed response URL covers it). The
91    /// holder of a lease that expired without a successor may still report.
92    Lease(String),
93    /// The caller only claims this lease id, for example a bearer token with a
94    /// `lease_id` query. A lease record for exactly this lease must exist.
95    HeldLease(String),
96    /// The command was never leased (push delivery), so no lease may exist.
97    NeverLeased,
98}
99
100/// Deadline index data
101#[derive(Debug, Clone, Serialize, Deserialize)]
102struct DeadlineIndexData {
103    pub command_id: String,
104    pub deadline: DateTime<Utc>,
105}
106
107// =============================================================================
108// Command Server
109// =============================================================================
110
111/// Core command server implementation.
112///
113/// Uses CommandRegistry as source of truth for metadata.
114/// Uses KV for operational data (params, responses, indices, leases).
115pub struct CommandServer {
116    kv: Arc<dyn Kv>,
117    storage: Arc<dyn Storage>,
118    command_dispatcher: Arc<dyn CommandDispatcher>,
119    command_registry: Arc<dyn CommandRegistry>,
120    inline_max_bytes: usize,
121    base_url: String,
122    response_signing_key: Vec<u8>,
123    clock: Arc<dyn Fn() -> DateTime<Utc> + Send + Sync>,
124}
125
126impl CommandServer {
127    /// True only when the configured registry can atomically persist typed
128    /// operation result contracts before command execution becomes possible.
129    pub fn persists_operation_result_contract(&self) -> bool {
130        self.command_registry.persists_operation_result_contract()
131    }
132
133    /// Create a new command server instance
134    pub fn new(
135        kv: Arc<dyn Kv>,
136        storage: Arc<dyn Storage>,
137        command_dispatcher: Arc<dyn CommandDispatcher>,
138        command_registry: Arc<dyn CommandRegistry>,
139        base_url: String,
140        response_signing_key: Vec<u8>,
141    ) -> Self {
142        Self {
143            kv,
144            storage,
145            command_dispatcher,
146            command_registry,
147            inline_max_bytes: INLINE_MAX_BYTES,
148            base_url,
149            response_signing_key,
150            clock: Arc::new(Utc::now),
151        }
152    }
153
154    /// Create a new command server with custom inline size limit
155    pub fn with_inline_limit(
156        kv: Arc<dyn Kv>,
157        storage: Arc<dyn Storage>,
158        command_dispatcher: Arc<dyn CommandDispatcher>,
159        command_registry: Arc<dyn CommandRegistry>,
160        base_url: String,
161        inline_max_bytes: usize,
162        response_signing_key: Vec<u8>,
163    ) -> Self {
164        Self {
165            kv,
166            storage,
167            command_dispatcher,
168            command_registry,
169            inline_max_bytes,
170            base_url,
171            response_signing_key,
172            clock: Arc::new(Utc::now),
173        }
174    }
175
176    /// Set the trusted server clock used for credential and lease deadlines.
177    pub fn with_clock(mut self, clock: Arc<dyn Fn() -> DateTime<Utc> + Send + Sync>) -> Self {
178        self.clock = clock;
179        self
180    }
181
182    fn now(&self) -> DateTime<Utc> {
183        (self.clock)()
184    }
185
186    fn remaining_authority(&self, deadline: DateTime<Utc>) -> Result<Duration> {
187        // Storage signers accept relative whole-second lifetimes. Reserve a
188        // second for signing work, then check the returned absolute expiry too.
189        let seconds = (deadline - self.now()).num_seconds() - 1;
190        if seconds <= 0 {
191            return Err(AlienError::new(ErrorData::CommandAuthorityExpired));
192        }
193        Ok(Duration::from_secs(seconds as u64))
194    }
195
196    fn check_storage_deadline(
197        &self,
198        request: &PresignedRequest,
199        deadline: DateTime<Utc>,
200    ) -> Result<()> {
201        if request.expiration > deadline || self.now() >= deadline {
202            return Err(AlienError::new(ErrorData::CommandAuthorityExpired));
203        }
204        Ok(())
205    }
206
207    /// Maximum allowed response token lifetime (2 hours).
208    const MAX_RESPONSE_TOKEN_LIFETIME_SECS: i64 = 7200;
209    /// Worker execution can run for 1 hour and the operator lease adds 60
210    /// seconds of response-submission headroom. Response credentials therefore
211    /// need to outlive both; 2 hours stays within the verifier cap.
212    const RESPONSE_CREDENTIAL_LIFETIME_SECS: u64 = 7200;
213
214    /// Sign a response URL for a specific command, and for one lease of it when
215    /// the command was leased to a polling receiver.
216    ///
217    /// Returns `(hmac_hex, expires_epoch)`. The HMAC is computed over
218    /// `"commands.v1:{command_id}:{expires}"`, or
219    /// `"commands.v2:{command_id}:{lease_id}:{expires}"` for a lease, using the
220    /// server's signing key.
221    fn sign_response_url(
222        &self,
223        command_id: &str,
224        lease_id: Option<&str>,
225        deadline: DateTime<Utc>,
226    ) -> (String, i64) {
227        let expires = deadline.timestamp();
228        let token = self
229            .response_mac(command_id, lease_id, expires)
230            .finalize()
231            .into_bytes();
232        (hex::encode(token), expires)
233    }
234
235    fn response_mac(&self, command_id: &str, lease_id: Option<&str>, expires: i64) -> HmacSha256 {
236        let message = match lease_id {
237            Some(lease_id) => format!("commands.v2:{command_id}:{lease_id}:{expires}"),
238            None => format!("commands.v1:{command_id}:{expires}"),
239        };
240        let mut mac =
241            HmacSha256::new_from_slice(&self.response_signing_key).expect("HMAC accepts any key");
242        mac.update(message.as_bytes());
243        mac
244    }
245
246    /// Verify a response token for a specific command, and for the lease it
247    /// names when the URL carries one. A token signed for a lease does not
248    /// verify without it, so the lease cannot be dropped from the URL.
249    ///
250    /// Performs HMAC verification first (constant-time), then checks expiration,
251    /// to avoid leaking timing information about token validity windows.
252    pub fn verify_response_token(
253        &self,
254        command_id: &str,
255        lease_id: Option<&str>,
256        token: &str,
257        expires: i64,
258    ) -> bool {
259        // Validate token format: SHA-256 HMAC = 32 bytes = 64 hex chars.
260        if token.len() != 64 {
261            return false;
262        }
263
264        let mac = self.response_mac(command_id, lease_id, expires);
265
266        // Decode hex and verify HMAC (constant-time comparison).
267        let Ok(token_bytes) = hex::decode(token) else {
268            return false;
269        };
270        let hmac_valid = mac.verify_slice(&token_bytes).is_ok();
271
272        // Check expiration and max lifetime AFTER HMAC to avoid timing leaks.
273        let now = self.now().timestamp();
274        let not_expired = now < expires;
275        let within_max_lifetime = expires <= now + Self::MAX_RESPONSE_TOKEN_LIFETIME_SECS;
276
277        hmac_valid && not_expired && within_max_lifetime
278    }
279
280    /// Whether the command is currently held by a lease, or was last held by
281    /// one that expired. A response to such a command must name its lease.
282    pub async fn command_is_leased(&self, command_id: &str) -> Result<bool> {
283        let key = format!("cmd:{command_id}:lease");
284        Ok(self
285            .kv
286            .get(&key)
287            .await
288            .context(ErrorData::KvOperationFailed {
289                operation: "get".to_string(),
290                key,
291                message: "Failed to read the command lease".to_string(),
292            })?
293            .is_some())
294    }
295
296    /// Claim the command's lease slot for a response, atomically.
297    ///
298    /// A command is held by one lease at a time. A holder whose lease expired
299    /// without a successor may still report what it ran, but once the command
300    /// was leased again the new holder is the one running it. The claim is a
301    /// conditional write on the lease record, so a lease taken between reading
302    /// it and answering cannot be overtaken: the claim then fails with
303    /// `LeaseSuperseded`.
304    ///
305    /// - A live lease record of the expected lease is rewritten as claimed,
306    ///   conditioned on the version that was read. It keeps its expiry, so a
307    ///   failed response does not extend it.
308    /// - An absent record (released, or expired without a successor) refuses a
309    ///   `HeldLease`. For a signed `Lease` it is replaced by a short claim
310    ///   written only if the key is still absent.
311    ///   Acquiring a lease also writes only if the key is absent, so the two
312    ///   cannot both succeed.
313    /// - Any other lease record, or any record when no lease is expected,
314    ///   refuses the response.
315    async fn claim_lease_for_response(
316        &self,
317        command_id: &str,
318        expected: &ExpectedLease,
319    ) -> Result<()> {
320        const CLAIM_SECS: u64 = 60;
321        const ATTEMPTS: usize = 8;
322        let key = format!("cmd:{command_id}:lease");
323        let expected_id = match expected {
324            ExpectedLease::Lease(lease_id) | ExpectedLease::HeldLease(lease_id) => {
325                lease_id.as_str()
326            }
327            ExpectedLease::NeverLeased => "",
328        };
329        let superseded = || {
330            AlienError::new(ErrorData::LeaseSuperseded {
331                command_id: command_id.to_string(),
332                lease_id: expected_id.to_string(),
333            })
334        };
335        let kv_error = |operation: &str, message: &str| ErrorData::KvOperationFailed {
336            operation: operation.to_string(),
337            key: key.clone(),
338            message: message.to_string(),
339        };
340        let serialize = |lease: &LeaseData| {
341            serde_json::to_vec(lease)
342                .into_alien_error()
343                .context(ErrorData::SerializationFailed {
344                    message: "Failed to serialize lease data".to_string(),
345                    data_type: Some("LeaseData".to_string()),
346                })
347        };
348
349        for _ in 0..ATTEMPTS {
350            let entry = self
351                .kv
352                .get(&key)
353                .await
354                .context(kv_error("get", "Failed to read the command lease"))?;
355            match entry {
356                Some(entry) => {
357                    let mut lease: LeaseData = serde_json::from_slice(&entry.value)
358                        .into_alien_error()
359                        .context(ErrorData::SerializationFailed {
360                            message: "Failed to deserialize lease data".to_string(),
361                            data_type: Some("LeaseData".to_string()),
362                        })?;
363                    // "Never leased" matches only the claim an earlier attempt
364                    // of this same response left (empty lease id), never a
365                    // claim or lease held under a real lease id.
366                    let matches_expected = match expected {
367                        ExpectedLease::Lease(id) | ExpectedLease::HeldLease(id) => {
368                            *id == lease.lease_id
369                        }
370                        ExpectedLease::NeverLeased => lease.lease_id.is_empty() && lease.completing,
371                    };
372                    if !matches_expected {
373                        return Err(superseded());
374                    }
375                    if lease.completing {
376                        return Ok(());
377                    }
378                    lease.completing = true;
379                    let remaining = (lease.expires_at - self.now()).num_seconds().max(1) as u64;
380                    let claimed = self
381                        .kv
382                        .put(
383                            &key,
384                            serialize(&lease)?,
385                            Some(PutOptions {
386                                ttl: Some(Duration::from_secs(remaining)),
387                                condition: PutCondition::Version(entry.version),
388                            }),
389                        )
390                        .await
391                        .context(kv_error("put", "Failed to claim the command lease"))?;
392                    if claimed {
393                        return Ok(());
394                    }
395                }
396                None => {
397                    // Nothing proves an unsigned lease id once its record is
398                    // gone, so it cannot report.
399                    if matches!(expected, ExpectedLease::HeldLease(_)) {
400                        return Err(superseded());
401                    }
402                    let now = self.now();
403                    let claim = LeaseData {
404                        lease_id: expected_id.to_string(),
405                        acquired_at: now,
406                        expires_at: now + chrono::Duration::seconds(CLAIM_SECS as i64),
407                        owner: "response".to_string(),
408                        completing: true,
409                    };
410                    let claimed = self
411                        .kv
412                        .put(
413                            &key,
414                            serialize(&claim)?,
415                            Some(PutOptions {
416                                ttl: Some(Duration::from_secs(CLAIM_SECS)),
417                                condition: PutCondition::Absent,
418                            }),
419                        )
420                        .await
421                        .context(kv_error("put", "Failed to claim the command lease"))?;
422                    if claimed {
423                        return Ok(());
424                    }
425                }
426            }
427        }
428        Err(superseded())
429    }
430
431    /// Submit a command's response from the holder of `expected`. The lease is
432    /// claimed with a conditional write before anything is stored, so a lease
433    /// that was superseded, even a moment ago, cannot complete the command.
434    pub async fn submit_command_response_for_lease(
435        &self,
436        command_id: &str,
437        response: CommandResponse,
438        expected: ExpectedLease,
439    ) -> Result<()> {
440        // An empty lease id names no lease.
441        let expected = match expected {
442            ExpectedLease::Lease(id) | ExpectedLease::HeldLease(id) if id.is_empty() => {
443                ExpectedLease::NeverLeased
444            }
445            other => other,
446        };
447        self.claim_lease_for_response(command_id, &expected).await?;
448        self.submit_command_response(command_id, response).await?;
449        // A duplicate response to a finished command returns early above and
450        // leaves its claim behind; drop it rather than wait for the expiry.
451        let _ = self.delete_lease(command_id).await;
452        Ok(())
453    }
454
455    // =========================================================================
456    // Public API Methods
457    // =========================================================================
458
459    /// Create a new command.
460    ///
461    /// Flow:
462    /// 1. Validate request
463    /// 2. Registry creates command metadata (source of truth)
464    /// 3. KV stores params blob
465    /// 4. KV creates pending index (for Pull) or dispatch (for Push)
466    pub async fn create_command(
467        &self,
468        request: CreateCommandRequest,
469    ) -> Result<CreateCommandResponse> {
470        // Validate the request
471        self.validate_create_command(&request).await?;
472
473        // Resolve which command-capable resource this command targets
474        // (explicit targetResourceId, or single-target shorthand).
475        let resolved_target = self
476            .command_registry
477            .resolve_target(
478                &request.deployment_id,
479                &request.command,
480                request.target_resource_id.as_deref(),
481            )
482            .await?;
483
484        // Compose the target-scoped idempotency key once, from the resolved
485        // target, and reuse it for both the pre-create check and the
486        // post-create mapping. Both must derive from the same target, so a
487        // single composition is the source of truth (idempotency is scoped per
488        // target: the same key addressed to two different targets is two
489        // commands).
490        let composed_idempotency_key = request.idempotency_key.as_ref().map(|idem_key| {
491            Self::compose_idempotency_key(
492                &request.deployment_id,
493                &resolved_target.target.resource_id,
494                &request.command,
495                idem_key,
496            )
497        });
498
499        // Check idempotency if key provided.
500        if let Some(ref composed_key) = composed_idempotency_key {
501            if let Some(existing_id) = self.check_idempotency(composed_key).await? {
502                // Return existing command status
503                let status = self
504                    .command_registry
505                    .get_command_status(&existing_id)
506                    .await?;
507                if let Some(s) = status {
508                    return Ok(CreateCommandResponse {
509                        command_id: existing_id,
510                        created: false,
511                        state: s.state,
512                        storage_upload: None,
513                        inline_allowed_up_to: self.inline_max_bytes as u64,
514                        next: "poll".to_string(),
515                    });
516                }
517            }
518        }
519
520        // Determine initial state and request size
521        let (initial_state, request_size_bytes) = match &request.params {
522            BodySpec::Inline { inline_base64 } => {
523                let size = inline_base64.len() as u64;
524                (CommandState::Pending, Some(size))
525            }
526            BodySpec::Storage { size, .. } => {
527                if size.unwrap_or(0) > self.inline_max_bytes as u64 {
528                    (CommandState::PendingUpload, *size)
529                } else {
530                    (CommandState::Pending, *size)
531                }
532            }
533        };
534
535        // 1. Registry creates command metadata (SOURCE OF TRUTH)
536        let metadata = self
537            .command_registry
538            .create_command(
539                &request.deployment_id,
540                &request.command,
541                &resolved_target,
542                initial_state,
543                request.deadline,
544                request_size_bytes,
545                request.operation_result_contract.clone(),
546            )
547            .await?;
548
549        let command_id = metadata.command_id;
550        let delivery_mode = metadata.delivery_mode;
551
552        // 2. Store idempotency mapping in KV, reusing the key composed above
553        // from the same resolved target. Losing the conditional put means a
554        // concurrent create with the same key raced past the pre-create check
555        // together with this one; dedupe by failing the command created above
556        // and answering with the winner's, so the caller never observes two
557        // live commands for one idempotency key.
558        if let Some(ref composed_key) = composed_idempotency_key {
559            if let Some(winner_id) = self.store_idempotency(composed_key, &command_id).await? {
560                let _ = self
561                    .command_registry
562                    .complete_command(
563                        &command_id,
564                        CommandState::Failed,
565                        self.now(),
566                        None,
567                        Some(serde_json::json!({
568                            "code": "IDEMPOTENT_DUPLICATE",
569                            "message": format!(
570                                "Superseded by concurrent create '{}' with the same idempotency key",
571                                winner_id
572                            ),
573                        })),
574                    )
575                    .await?;
576                let status = self.command_registry.get_command_status(&winner_id).await?;
577                let state = status.map(|s| s.state).unwrap_or(CommandState::Pending);
578                return Ok(CreateCommandResponse {
579                    command_id: winner_id,
580                    created: false,
581                    state,
582                    storage_upload: None,
583                    inline_allowed_up_to: self.inline_max_bytes as u64,
584                    next: "poll".to_string(),
585                });
586            }
587        }
588
589        // 3. Store params in KV
590        self.store_params(&command_id, &request.params).await?;
591
592        // 4. Generate storage upload URL if needed
593        let storage_upload = if initial_state == CommandState::PendingUpload {
594            Some(self.generate_params_upload(&command_id).await?)
595        } else {
596            None
597        };
598
599        // 5. Handle dispatch based on state and the target's delivery mode
600        let (final_state, next_action) = if initial_state == CommandState::Pending {
601            match delivery_mode {
602                CommandDeliveryMode::Push => {
603                    // Push delivery: dispatch immediately
604                    let state = self
605                        .dispatch_command_push(&command_id, &request.deployment_id)
606                        .await?;
607                    (state, "poll")
608                }
609                CommandDeliveryMode::Pull => {
610                    // Pull delivery: create a pending index for a receiver or
611                    // environment-local operator relay.
612                    self.create_pending_index(
613                        &request.deployment_id,
614                        &metadata.target.resource_id,
615                        &command_id,
616                    )
617                    .await?;
618                    debug!("Command {} ready for target-scoped lease", command_id);
619                    (CommandState::Pending, "poll")
620                }
621            }
622        } else {
623            // PendingUpload - need upload first
624            (initial_state, "upload")
625        };
626
627        // 6. Create deadline index if deadline provided
628        if let Some(deadline) = request.deadline {
629            self.create_deadline_index(&command_id, deadline).await?;
630        }
631
632        Ok(CreateCommandResponse {
633            command_id,
634            created: true,
635            state: final_state,
636            storage_upload,
637            inline_allowed_up_to: self.inline_max_bytes as u64,
638            next: next_action.to_string(),
639        })
640    }
641
642    /// Mark upload as complete and dispatch command.
643    pub async fn upload_complete(
644        &self,
645        command_id: &str,
646        upload_request: UploadCompleteRequest,
647    ) -> Result<UploadCompleteResponse> {
648        // 1. Get current status from registry (source of truth)
649        let status = self
650            .command_registry
651            .get_command_status(command_id)
652            .await?
653            .ok_or_else(|| {
654                AlienError::new(ErrorData::CommandNotFound {
655                    command_id: command_id.to_string(),
656                })
657            })?;
658
659        // 2. Validate current state
660        if status.state != CommandState::PendingUpload {
661            return Err(AlienError::new(ErrorData::InvalidStateTransition {
662                from: status.state.as_ref().to_string(),
663                to: CommandState::Pending.as_ref().to_string(),
664            }));
665        }
666
667        // 3. Update params in KV with storage reference
668        let storage_get_request = self.generate_storage_get_request(command_id).await?;
669        let params = BodySpec::Storage {
670            size: Some(upload_request.size),
671            storage_get_request: Some(storage_get_request),
672            storage_put_used: None,
673        };
674        self.store_params(command_id, &params).await?;
675
676        // 4. Update registry to Pending state
677        let transitioned = self
678            .command_registry
679            .update_command_state(command_id, CommandState::Pending, None, None, None, None)
680            .await?;
681        if !transitioned {
682            let current_state = self
683                .command_registry
684                .get_command_status(command_id)
685                .await?
686                .map(|current| current.state)
687                .unwrap_or(status.state);
688            return Err(AlienError::new(ErrorData::InvalidStateTransition {
689                from: current_state.as_ref().to_string(),
690                to: CommandState::Pending.as_ref().to_string(),
691            }));
692        }
693
694        // 5. Get delivery mode from registry and handle dispatch
695        let metadata = self
696            .command_registry
697            .get_command_metadata(command_id)
698            .await?
699            .ok_or_else(|| {
700                AlienError::new(ErrorData::CommandNotFound {
701                    command_id: command_id.to_string(),
702                })
703            })?;
704
705        let final_state = match metadata.delivery_mode {
706            CommandDeliveryMode::Push => {
707                self.dispatch_command_push(command_id, &status.deployment_id)
708                    .await?
709            }
710            CommandDeliveryMode::Pull => {
711                self.create_pending_index(
712                    &status.deployment_id,
713                    &metadata.target.resource_id,
714                    command_id,
715                )
716                .await?;
717                debug!(
718                    "Command {} ready for pull after upload (target will poll)",
719                    command_id
720                );
721                CommandState::Pending
722            }
723        };
724
725        Ok(UploadCompleteResponse {
726            command_id: command_id.to_string(),
727            state: final_state,
728        })
729    }
730
731    /// Get command status.
732    ///
733    /// Queries registry for metadata (source of truth), KV for response blob.
734    pub async fn get_command_status(&self, command_id: &str) -> Result<CommandStatusResponse> {
735        // 1. Get status from registry (SOURCE OF TRUTH)
736        let status = self
737            .command_registry
738            .get_command_status(command_id)
739            .await?
740            .ok_or_else(|| {
741                AlienError::new(ErrorData::CommandNotFound {
742                    command_id: command_id.to_string(),
743                })
744            })?;
745
746        // 2. Check deadline expiry inline
747        if let Some(deadline) = status.deadline {
748            if self.now() > deadline && !status.state.is_terminal() {
749                // Expire the command — CONDITIONALLY: a submit can land
750                // between the status read above and this write, and an
751                // unconditional write would stomp its terminal state (the
752                // torn-record class the conditional transition exists for).
753                let won = self
754                    .command_registry
755                    .complete_command(command_id, CommandState::Expired, self.now(), None, None)
756                    .await?;
757                if won {
758                    // Clean up pending index
759                    self.delete_pending_index(
760                        &status.deployment_id,
761                        &status.target.resource_id,
762                        command_id,
763                    )
764                    .await?;
765
766                    // Return expired status directly (avoid recursion)
767                    return Ok(CommandStatusResponse {
768                        command_id: command_id.to_string(),
769                        state: CommandState::Expired,
770                        attempt: status.attempt,
771                        target: status.target,
772                        response: None,
773                    });
774                }
775                // Lost to a concurrent submit: fall through and serve the
776                // freshly-terminal state below.
777                let status = self
778                    .command_registry
779                    .get_command_status(command_id)
780                    .await?
781                    .ok_or_else(|| {
782                        AlienError::new(ErrorData::CommandNotFound {
783                            command_id: command_id.to_string(),
784                        })
785                    })?;
786                let response = if status.state.is_terminal() {
787                    self.get_response(command_id).await?
788                } else {
789                    None
790                };
791                return Ok(CommandStatusResponse {
792                    command_id: command_id.to_string(),
793                    state: status.state,
794                    attempt: status.attempt,
795                    target: status.target,
796                    response,
797                });
798            }
799        }
800
801        // 3. Get response blob from KV if terminal state
802        let response = if status.state.is_terminal() {
803            self.get_response(command_id).await?
804        } else {
805            None
806        };
807
808        Ok(CommandStatusResponse {
809            command_id: command_id.to_string(),
810            state: status.state,
811            attempt: status.attempt,
812            target: status.target,
813            response,
814        })
815    }
816
817    /// Submit response from deployment.
818    ///
819    /// Stores response blob in KV, updates state in registry.
820    pub async fn submit_command_response(
821        &self,
822        command_id: &str,
823        mut response: CommandResponse,
824    ) -> Result<()> {
825        // 1. Get current status from registry
826        let status = self
827            .command_registry
828            .get_command_status(command_id)
829            .await?
830            .ok_or_else(|| {
831                AlienError::new(ErrorData::CommandNotFound {
832                    command_id: command_id.to_string(),
833                })
834            })?;
835
836        // 2. Handle duplicate responses gracefully
837        if status.state.is_terminal() {
838            debug!(
839                "Ignoring duplicate response for terminal command {}",
840                command_id
841            );
842            return Ok(());
843        }
844
845        // 3. Validate state transition
846        if status.state != CommandState::Dispatched {
847            return Err(AlienError::new(ErrorData::InvalidStateTransition {
848                from: status.state.as_ref().to_string(),
849                to: CommandState::Succeeded.as_ref().to_string(),
850            }));
851        }
852
853        // 4. If response was uploaded to storage, generate download URL
854        if let CommandResponse::Success {
855            response: ref mut body,
856        } = response
857        {
858            if let BodySpec::Storage {
859                size,
860                storage_get_request,
861                storage_put_used,
862            } = body
863            {
864                if storage_get_request.is_none() && storage_put_used.unwrap_or(false) {
865                    let get_request = self
866                        .generate_response_storage_get_request(command_id)
867                        .await?;
868                    *body = BodySpec::Storage {
869                        size: *size,
870                        storage_get_request: Some(get_request),
871                        storage_put_used: *storage_put_used,
872                    };
873                }
874            }
875        }
876
877        // 5. Store response blob in KV
878        self.store_response(command_id, &response).await?;
879
880        // 6. Update registry state (SOURCE OF TRUTH) BEFORE cleaning up the lease
881        // and pending index. Committing the terminal state first guarantees the
882        // command can never be stranded as Dispatched-with-no-lease-no-index: if
883        // the process dies (or a cleanup step errors) after this point, get/poll
884        // sees the terminal state and returns the already-stored response, and any
885        // orphaned lease/pending-index entry is reaped by `acquire_lease`'s
886        // terminal-state check. The old order (cleanup first, state last) left a
887        // crash window in which the response was stored but permanently invisible.
888        let (new_state, error) = if response.is_success() {
889            (CommandState::Succeeded, None)
890        } else if let CommandResponse::Error { code, message, .. } = &response {
891            (
892                CommandState::Failed,
893                Some(serde_json::json!({ "code": code, "message": message })),
894            )
895        } else {
896            (CommandState::Failed, None)
897        };
898
899        let response_size = match &response {
900            CommandResponse::Success {
901                response: BodySpec::Inline { inline_base64 },
902            } => Some(inline_base64.len() as u64),
903            CommandResponse::Success {
904                response: BodySpec::Storage { size, .. },
905            } => *size,
906            _ => None,
907        };
908
909        // Conditional terminal transition: exactly one of two racing
910        // submitters (a redelivered execution racing the original whose lease
911        // expired) wins; a terminal record is never overwritten. The blob was
912        // pre-stored above for crash-safety (state never flips terminal with
913        // no blob on disk); the winner re-stores its own response below so
914        // the recorded state and the served blob agree. Residual: a loser
915        // whose pre-store lands after the winner's re-store can still leave
916        // its blob — that requires the loser's KV write to outlast the
917        // winner's entire transition+re-store, a pathological schedule.
918        let won = self
919            .command_registry
920            .complete_command(command_id, new_state, self.now(), response_size, error)
921            .await?;
922        if !won {
923            debug!(
924                "Ignoring duplicate response for command {} (lost the terminal transition race)",
925                command_id
926            );
927            return Ok(());
928        }
929        self.store_response(command_id, &response).await?;
930
931        // 7. Clean up lease from KV (best-effort; the terminal state is already
932        // committed above, so a failure here cannot strand the command). Log a
933        // warning and continue instead of failing the call — a leftover entry
934        // is reaped by `acquire_lease`'s terminal-state check on its next scan.
935        if let Err(e) = self.delete_lease(command_id).await {
936            warn!(
937                command_id,
938                error = %e,
939                "Failed to clean up lease after terminal response; will be reaped on next lease scan"
940            );
941        }
942
943        // 8. Clean up pending index from KV (best-effort; terminal state).
944        // Same reasoning as the lease cleanup above.
945        if let Err(e) = self
946            .delete_pending_index(
947                &status.deployment_id,
948                &status.target.resource_id,
949                command_id,
950            )
951            .await
952        {
953            warn!(
954                command_id,
955                error = %e,
956                "Failed to clean up pending index after terminal response; will be reaped on next lease scan"
957            );
958        }
959
960        info!(
961            "Command {} completed with state {:?}",
962            command_id, new_state
963        );
964        Ok(())
965    }
966
967    /// Acquire leases for polling deployments.
968    ///
969    /// Scans KV pending index, queries registry for metadata, creates leases in KV.
970    pub async fn acquire_lease(
971        &self,
972        deployment_id: &str,
973        lease_request: &LeaseRequest,
974    ) -> Result<LeaseResponse> {
975        self.acquire_lease_with_deadline(deployment_id, lease_request, None)
976            .await
977    }
978
979    /// Lease commands without delegating response or storage authority beyond
980    /// the authenticated receiver's absolute deadline. None retains legacy policy.
981    pub async fn acquire_lease_with_deadline(
982        &self,
983        deployment_id: &str,
984        lease_request: &LeaseRequest,
985        authority_deadline: Option<DateTime<Utc>>,
986    ) -> Result<LeaseResponse> {
987        if let Some(deadline) = authority_deadline {
988            self.remaining_authority(deadline)?;
989        }
990        let mut leases = Vec::new();
991
992        // 1. Scan KV pending index — ONLY the requesting target's prefix.
993        // Commands for other targets in the same deployment are invisible here.
994        let target_prefix = format!(
995            "target:{}:{}:pending:",
996            deployment_id, lease_request.target.resource_id
997        );
998        let scan_result = self
999            .kv
1000            .scan_prefix(&target_prefix, Some(lease_request.max_leases * 2), None)
1001            .await
1002            .into_alien_error()
1003            .context(ErrorData::KvOperationFailed {
1004                operation: "scan_prefix".to_string(),
1005                key: target_prefix.clone(),
1006                message: "Failed to scan for pending commands".to_string(),
1007            })?;
1008
1009        for entry in scan_result.items {
1010            let index_key = entry.key;
1011            if leases.len() >= lease_request.max_leases {
1012                break;
1013            }
1014
1015            let command_id = self.extract_command_id_from_index_key(&index_key)?;
1016
1017            // 2. Try to acquire lease atomically in KV
1018            let lease_id = format!("lease_{}", Uuid::new_v4());
1019            let lease_duration = Duration::from_secs(lease_request.lease_seconds);
1020            let expires_at =
1021                Utc::now() + chrono::Duration::seconds(lease_request.lease_seconds as i64);
1022
1023            let lease_data = LeaseData {
1024                lease_id: lease_id.clone(),
1025                acquired_at: Utc::now(),
1026                expires_at,
1027                owner: deployment_id.to_string(),
1028                completing: false,
1029            };
1030
1031            let lease_key = format!("cmd:{}:lease", command_id);
1032            let lease_value = serde_json::to_vec(&lease_data).into_alien_error().context(
1033                ErrorData::SerializationFailed {
1034                    message: "Failed to serialize lease data".to_string(),
1035                    data_type: Some("LeaseData".to_string()),
1036                },
1037            )?;
1038
1039            let options = Some(PutOptions {
1040                ttl: Some(lease_duration),
1041                condition: PutCondition::Absent,
1042            });
1043
1044            let success = self
1045                .kv
1046                .put(&lease_key, lease_value, options)
1047                .await
1048                .context(ErrorData::KvOperationFailed {
1049                    operation: "put".to_string(),
1050                    key: lease_key.clone(),
1051                    message: "Failed to create lease".to_string(),
1052                })?;
1053
1054            if !success {
1055                // Lease already exists, skip
1056                continue;
1057            }
1058
1059            // Reverse index for O(1) release-by-lease-id lookups. Shares the
1060            // lease's TTL so it self-cleans on expiry; a stale entry is
1061            // harmless because every reader re-verifies the lease_id against
1062            // the live `cmd:{id}:lease` record.
1063            let reverse_key = format!("lease:{}", lease_id);
1064            self.kv
1065                .put(
1066                    &reverse_key,
1067                    command_id.as_bytes().to_vec(),
1068                    Some(PutOptions {
1069                        ttl: Some(lease_duration),
1070                        condition: PutCondition::None,
1071                    }),
1072                )
1073                .await
1074                .context(ErrorData::KvOperationFailed {
1075                    operation: "put".to_string(),
1076                    key: reverse_key,
1077                    message: "Failed to create lease reverse index".to_string(),
1078                })?;
1079
1080            // 3. Get metadata from registry
1081            let mut metadata = match self
1082                .command_registry
1083                .get_command_metadata(&command_id)
1084                .await?
1085            {
1086                Some(m) => m,
1087                None => {
1088                    // Command doesn't exist in registry, clean up
1089                    self.delete_lease(&command_id).await?;
1090                    let _ = self.kv.delete(&index_key, None).await;
1091                    continue;
1092                }
1093            };
1094
1095            // 3.1 Expiry-driven redelivery: this command was already
1096            // dispatched, yet the lease slot was free (the conditional put
1097            // above succeeded) — the previous lease TTL-expired with no
1098            // response and no explicit release. Increment the attempt so the
1099            // redelivered envelope carries `attempt > 1`, the at-least-once
1100            // redelivery signal both receiver twins document. The explicit
1101            // release path (`release_lease`) increments the same counter.
1102            if metadata.state == CommandState::Dispatched {
1103                self.command_registry.increment_attempt(&command_id).await?;
1104                metadata.attempt += 1;
1105            }
1106
1107            // 3.5 Defense-in-depth: the pending index key said this command
1108            // belongs to the requesting target — verify the registry agrees.
1109            // A mismatch means the index is corrupt; fail loudly rather than
1110            // delivering a command to the wrong resource. The corrupt index
1111            // key is deliberately retained (only the lease is cleaned up):
1112            // genuine corruption should never occur, and the key is the
1113            // evidence an operator needs — do not "fix" this by deleting it.
1114            if metadata.target != lease_request.target {
1115                self.delete_lease(&command_id).await?;
1116                return Err(AlienError::new(ErrorData::Other {
1117                    message: format!(
1118                        "Pending index corruption: command '{}' is indexed under target '{}' \
1119                         but the registry says it belongs to target '{}' — refusing to deliver",
1120                        command_id, lease_request.target.resource_id, metadata.target.resource_id,
1121                    ),
1122                }));
1123            }
1124
1125            // 4. Check if command is in terminal state (stale index)
1126            if metadata.state.is_terminal() {
1127                // Clean up stale data
1128                self.delete_lease(&command_id).await?;
1129                let _ = self.kv.delete(&index_key, None).await;
1130                continue;
1131            }
1132
1133            // 5. Check deadline expiry — conditionally: a racing submit's
1134            // terminal state must never be stomped back to Expired.
1135            if let Some(deadline) = metadata.deadline {
1136                if Utc::now() > deadline {
1137                    let _ = self
1138                        .command_registry
1139                        .complete_command(
1140                            &command_id,
1141                            CommandState::Expired,
1142                            Utc::now(),
1143                            None,
1144                            None,
1145                        )
1146                        .await?;
1147                    self.delete_lease(&command_id).await?;
1148                    let _ = self.kv.delete(&index_key, None).await;
1149                    continue;
1150                }
1151            }
1152
1153            // 6. Get params from KV
1154            let params = match self.get_params(&command_id).await? {
1155                Some(p) => p,
1156                None => {
1157                    // No params, something went wrong
1158                    self.delete_lease(&command_id).await?;
1159                    continue;
1160                }
1161            };
1162
1163            // 7. Mark Dispatched — conditionally. Between the terminal
1164            // check in step 3.1 and here, the ORIGINAL holder of a
1165            // TTL-expired lease can still submit; handing out this lease
1166            // would re-execute a completed command and stomp its state.
1167            let dispatched = self
1168                .command_registry
1169                .mark_dispatched_if_not_terminal(&command_id, Utc::now())
1170                .await?;
1171            if !dispatched {
1172                debug!(
1173                    command_id = %command_id,
1174                    "Command turned terminal while leasing; releasing the lease"
1175                );
1176                self.delete_lease(&command_id).await?;
1177                let _ = self.kv.delete(&index_key, None).await;
1178                continue;
1179            }
1180
1181            // 8. Build envelope. Lease-served envelopes carry manager URLs
1182            // as path-relative references from the lease endpoint: a pull
1183            // consumer resolves them against the exact endpoint it reached,
1184            // preserving both a network-corrected origin and any reverse-
1185            // proxy path prefix the manager cannot know. Push envelopes keep
1186            // absolute URLs: push transports have no configured base, and
1187            // reaching the manager's public address is inherent to push
1188            // delivery.
1189            // The params download is needed right away, so it stays within the
1190            // receiver's credential. The result upload and response URL must
1191            // outlive that credential: a running command still has to be able
1192            // to report its result. They last as long as the lease, which the
1193            // receiver sizes to the command's execution time.
1194            let response_deadline = authority_deadline.map(|_| expires_at);
1195            let mut envelope = self
1196                .build_envelope(
1197                    &command_id,
1198                    &metadata,
1199                    params,
1200                    authority_deadline,
1201                    response_deadline,
1202                    Some(&lease_id),
1203                )
1204                .await?;
1205            Self::relativize_manager_urls(&mut envelope, &self.base_url);
1206
1207            leases.push(LeaseInfo {
1208                lease_id,
1209                lease_expires_at: expires_at,
1210                command_id: command_id.clone(),
1211                attempt: metadata.attempt,
1212                envelope,
1213            });
1214        }
1215
1216        Ok(LeaseResponse { leases })
1217    }
1218
1219    /// Rewrite manager-origin URLs in a lease-served envelope to references
1220    /// relative to that lease endpoint (see [`Self::acquire_lease`]). Only
1221    /// same-origin URLs can be made relative, so cloud-presigned storage URLs
1222    /// pass through byte-for-byte.
1223    fn relativize_manager_urls(envelope: &mut Envelope, base_url: &str) {
1224        let Ok(mut lease_endpoint) = reqwest::Url::parse(base_url) else {
1225            // An unparseable base cannot produce relative references; leave
1226            // the envelope absolute (the pre-relative behavior).
1227            return;
1228        };
1229        let Ok(mut segments) = lease_endpoint.path_segments_mut() else {
1230            return;
1231        };
1232        segments.pop_if_empty().push("commands").push("leases");
1233        drop(segments);
1234        lease_endpoint.set_query(None);
1235        lease_endpoint.set_fragment(None);
1236
1237        let relativize = |target: &mut String| {
1238            let Ok(mut target_url) = reqwest::Url::parse(target.as_str()) else {
1239                return;
1240            };
1241            let suffix = target
1242                .find(['?', '#'])
1243                .map(|index| target[index..].to_string())
1244                .unwrap_or_default();
1245            target_url.set_query(None);
1246            target_url.set_fragment(None);
1247            if let Some(relative) = lease_endpoint.make_relative(&target_url) {
1248                *target = format!("{relative}{suffix}");
1249            }
1250        };
1251
1252        relativize(&mut envelope.response_handling.submit_response_url);
1253        if let alien_core::presigned::PresignedRequestBackend::Http { url, .. } =
1254            &mut envelope.response_handling.storage_upload_request.backend
1255        {
1256            relativize(url);
1257        }
1258        if let BodySpec::Storage {
1259            storage_get_request: Some(request),
1260            ..
1261        } = &mut envelope.params
1262        {
1263            if let alien_core::presigned::PresignedRequestBackend::Http { url, .. } =
1264                &mut request.backend
1265            {
1266                relativize(url);
1267            }
1268        }
1269    }
1270
1271    /// Release a lease manually.
1272    ///
1273    /// Increments attempt count in registry, returns command to Pending state.
1274    pub async fn release_lease(&self, command_id: &str, lease_id: &str) -> Result<()> {
1275        let lease_key = format!("cmd:{}:lease", command_id);
1276
1277        // 1. Verify lease ownership
1278        if let Ok(Some(lease_data)) = self.kv.get(&lease_key).await {
1279            let lease: LeaseData = serde_json::from_slice(&lease_data.value)
1280                .into_alien_error()
1281                .context(ErrorData::SerializationFailed {
1282                    message: "Failed to deserialize lease data".to_string(),
1283                    data_type: Some("LeaseData".to_string()),
1284                })?;
1285
1286            if lease.lease_id != lease_id {
1287                return Err(AlienError::new(ErrorData::LeaseNotFound {
1288                    lease_id: lease_id.to_string(),
1289                }));
1290            }
1291
1292            // 2. Delete lease from KV (and its reverse index)
1293            self.delete_lease(command_id).await?;
1294            let _ = self.kv.delete(&format!("lease:{}", lease_id), None).await;
1295
1296            // 3. Return the command to Pending only while it is still
1297            // non-terminal. A racing response/deadline completion wins.
1298            let released = self
1299                .command_registry
1300                .update_command_state(command_id, CommandState::Pending, None, None, None, None)
1301                .await?;
1302            if released {
1303                // 4. Increment the attempt only for a command that was
1304                // actually released for redelivery.
1305                self.command_registry.increment_attempt(command_id).await?;
1306            }
1307
1308            // Note: Pending index is NOT removed on lease, so command is still there
1309            debug!(
1310                released,
1311                "Lease {} released for command {}", lease_id, command_id
1312            );
1313        }
1314
1315        Ok(())
1316    }
1317
1318    /// Get the deployment_id that owns a command.
1319    ///
1320    /// Used by the manager's auth layer to check whether the caller has access
1321    /// to a specific command without fetching the full status.
1322    pub async fn get_command_deployment_id(&self, command_id: &str) -> Result<Option<String>> {
1323        let status = self.command_registry.get_command_status(command_id).await?;
1324        Ok(status.map(|s| s.deployment_id))
1325    }
1326
1327    /// Get the command registry's canonical status record for authorization.
1328    pub async fn get_command_status_record(
1329        &self,
1330        command_id: &str,
1331    ) -> Result<Option<CommandStatus>> {
1332        self.command_registry.get_command_status(command_id).await
1333    }
1334
1335    /// Get the command's canonical ownership fields for route authorization.
1336    pub async fn get_command_access_context(
1337        &self,
1338        command_id: &str,
1339    ) -> Result<Option<CommandAccessContext>> {
1340        self.command_registry
1341            .get_command_access_context(command_id)
1342            .await
1343    }
1344
1345    /// Resolve a lease_id to `(command_id, owner_deployment_id)` via the
1346    /// `lease:{lease_id}` reverse index, re-verifying against the live lease
1347    /// record (the reverse entry can outlive a released lease briefly, and a
1348    /// command can have been re-leased under a new lease_id since).
1349    ///
1350    /// Used by the manager's auth layer to check that the caller may act on
1351    /// the deployment that holds the lease.
1352    pub async fn get_lease_owner(&self, lease_id: &str) -> Result<Option<(String, String)>> {
1353        let reverse_key = format!("lease:{}", lease_id);
1354        let Some(command_id_bytes) =
1355            self.kv
1356                .get(&reverse_key)
1357                .await
1358                .context(ErrorData::KvOperationFailed {
1359                    operation: "get".to_string(),
1360                    key: reverse_key.clone(),
1361                    message: "Failed to look up lease reverse index".to_string(),
1362                })?
1363        else {
1364            return Ok(None);
1365        };
1366        let command_id = String::from_utf8(command_id_bytes.value).map_err(|_| {
1367            AlienError::new(ErrorData::Other {
1368                message: format!("Lease reverse index '{}' is not valid UTF-8", reverse_key),
1369            })
1370        })?;
1371
1372        let lease_key = format!("cmd:{}:lease", command_id);
1373        let Some(lease_data) =
1374            self.kv
1375                .get(&lease_key)
1376                .await
1377                .context(ErrorData::KvOperationFailed {
1378                    operation: "get".to_string(),
1379                    key: lease_key,
1380                    message: "Failed to look up lease".to_string(),
1381                })?
1382        else {
1383            return Ok(None);
1384        };
1385        let lease: LeaseData = serde_json::from_slice(&lease_data.value)
1386            .into_alien_error()
1387            .context(ErrorData::SerializationFailed {
1388                message: "Failed to deserialize lease data".to_string(),
1389                data_type: Some("LeaseData".to_string()),
1390            })?;
1391        if lease.lease_id != lease_id {
1392            return Ok(None);
1393        }
1394
1395        Ok(Some((command_id, lease.owner)))
1396    }
1397
1398    /// Release a lease by lease_id only (for the API).
1399    pub async fn release_lease_by_id(&self, lease_id: &str) -> Result<()> {
1400        match self.get_lease_owner(lease_id).await? {
1401            Some((command_id, _owner)) => self.release_lease(&command_id, lease_id).await,
1402            None => Err(AlienError::new(ErrorData::LeaseNotFound {
1403                lease_id: lease_id.to_string(),
1404            })),
1405        }
1406    }
1407
1408    // =========================================================================
1409    // Internal Helper Methods
1410    // =========================================================================
1411
1412    async fn validate_create_command(&self, request: &CreateCommandRequest) -> Result<()> {
1413        validate_operation_result_contract_request(
1414            &request.command,
1415            request.operation_result_contract.is_some(),
1416            self.command_registry.persists_operation_result_contract(),
1417        )?;
1418
1419        if request.command.is_empty() {
1420            return Err(AlienError::new(ErrorData::InvalidCommand {
1421                message: "Command name cannot be empty".to_string(),
1422            }));
1423        }
1424
1425        // The command name occupies one segment of the `:`-delimited
1426        // idempotency key (`{dep}:{rid}:{command}:{key}`). A ':' in the name
1427        // would let it bleed into the client-key segment — which routinely
1428        // contains ':' — so (command="a:b", key="c") and (command="a",
1429        // key="b:c") would forge the same key and be treated as the same
1430        // command. Reject ':' here, mirroring the target-id colon guard, so the
1431        // command segment is always unambiguous.
1432        validate_command_name(&request.command)?;
1433
1434        if request.deployment_id.is_empty() {
1435            return Err(AlienError::new(ErrorData::InvalidCommand {
1436                message: "Deployment ID cannot be empty".to_string(),
1437            }));
1438        }
1439
1440        if let Some(deadline) = request.deadline {
1441            if deadline <= self.now() {
1442                return Err(AlienError::new(ErrorData::InvalidCommand {
1443                    message: "Deadline must be in the future".to_string(),
1444                }));
1445            }
1446        }
1447
1448        Ok(())
1449    }
1450
1451    // --- Idempotency ---
1452
1453    /// Compose the target-scoped idempotency key:
1454    /// `{deploymentId}:{targetResourceId}:{commandName}:{key}`.
1455    ///
1456    /// Scoping by target means the same client key addressed to two different
1457    /// targets creates two distinct commands.
1458    fn compose_idempotency_key(
1459        deployment_id: &str,
1460        target_resource_id: &str,
1461        command_name: &str,
1462        idem_key: &str,
1463    ) -> String {
1464        // Invariant: at every real call site the target id and command name are
1465        // both `:`-free (the former enforced at resolution via
1466        // `validate_command_target_id`, the latter via `validate_command_name`
1467        // in `validate_create_command`), so each occupies exactly one segment of
1468        // `{dep}:{rid}:{command}:{key}` and only the trailing client key may
1469        // carry ':'. Those guards live upstream; this is a pure formatter, so it
1470        // is not asserted on `command_name` here (the collision tests below
1471        // deliberately format a ':'-bearing command to demonstrate what the
1472        // upstream guard prevents).
1473        debug_assert!(
1474            !target_resource_id.contains(':'),
1475            "target_resource_id must be ':'-free before key composition: {target_resource_id}"
1476        );
1477        format!(
1478            "{}:{}:{}:{}",
1479            deployment_id, target_resource_id, command_name, idem_key
1480        )
1481    }
1482
1483    /// Preserve existing KV keys when portable, while supporting versioned
1484    /// commands (whose names contain '/') and arbitrary client keys. The v2
1485    /// prefix cannot overlap a key written by the legacy `idem:` scheme.
1486    fn storage_idempotency_key(composed_key: &str) -> String {
1487        let legacy_key = format!("idem:{composed_key}");
1488        if validate_key(&legacy_key).is_ok() {
1489            legacy_key
1490        } else {
1491            format!(
1492                "idem2:{}",
1493                hex::encode(Sha256::digest(composed_key.as_bytes()))
1494            )
1495        }
1496    }
1497
1498    async fn check_idempotency(&self, idem_key: &str) -> Result<Option<String>> {
1499        let key = Self::storage_idempotency_key(idem_key);
1500        if let Some(data) = self
1501            .kv
1502            .get(&key)
1503            .await
1504            .context(ErrorData::KvOperationFailed {
1505                operation: "get".to_string(),
1506                key: key.clone(),
1507                message: "Failed to check idempotency".to_string(),
1508            })?
1509        {
1510            let command_id = String::from_utf8(data.value).into_alien_error().context(
1511                ErrorData::SerializationFailed {
1512                    message: "Invalid idempotency data".to_string(),
1513                    data_type: Some("String".to_string()),
1514                },
1515            )?;
1516            return Ok(Some(command_id));
1517        }
1518        Ok(None)
1519    }
1520
1521    /// Claim the idempotency key for `command_id`.
1522    ///
1523    /// Returns `None` when this command won the key. Returns
1524    /// `Some(winner_id)` when a concurrent create with the same key won the
1525    /// conditional put first — both requests passed the pre-create
1526    /// `check_idempotency` before either stored, so the loser must be
1527    /// detected here, after its command was already created.
1528    async fn store_idempotency(&self, idem_key: &str, command_id: &str) -> Result<Option<String>> {
1529        let key = Self::storage_idempotency_key(idem_key);
1530        let ttl = Duration::from_secs(24 * 60 * 60); // 24 hours
1531        let won = self
1532            .kv
1533            .put(
1534                &key,
1535                command_id.as_bytes().to_vec(),
1536                Some(PutOptions {
1537                    ttl: Some(ttl),
1538                    condition: PutCondition::Absent,
1539                }),
1540            )
1541            .await
1542            .context(ErrorData::KvOperationFailed {
1543                operation: "put".to_string(),
1544                key: key.clone(),
1545                message: "Failed to store idempotency".to_string(),
1546            })?;
1547        if won {
1548            return Ok(None);
1549        }
1550        // Lost the conditional put: read back who won. The winner entry can
1551        // only be absent if it TTL-expired in the microseconds since — treat
1552        // that as an inconsistency rather than silently duplicating.
1553        match self.check_idempotency(idem_key).await? {
1554            Some(winner_id) => Ok(Some(winner_id)),
1555            None => Err(AlienError::new(ErrorData::Other {
1556                message: format!(
1557                    "Idempotency key '{}' was concurrently claimed but has no winner entry",
1558                    key
1559                ),
1560            })),
1561        }
1562    }
1563
1564    // --- Params ---
1565
1566    pub async fn store_params(&self, command_id: &str, params: &BodySpec) -> Result<()> {
1567        let key = format!("cmd:{}:params", command_id);
1568
1569        // Try serializing as-is first
1570        let data = CommandParamsData {
1571            params: params.clone(),
1572        };
1573        let value = serde_json::to_vec(&data).into_alien_error().context(
1574            ErrorData::SerializationFailed {
1575                message: "Failed to serialize params".to_string(),
1576                data_type: Some("CommandParamsData".to_string()),
1577            },
1578        )?;
1579
1580        // If it fits in KV, store directly (fast path)
1581        if value.len() <= KV_VALUE_THRESHOLD {
1582            self.kv
1583                .put(&key, value, None)
1584                .await
1585                .context(ErrorData::KvOperationFailed {
1586                    operation: "put".to_string(),
1587                    key: key.clone(),
1588                    message: "Failed to store params".to_string(),
1589                })?;
1590            return Ok(());
1591        }
1592
1593        // Auto-promote: inline data exceeds KV limit, store raw bytes in blob
1594        if let BodySpec::Inline { inline_base64 } = params {
1595            let raw_bytes = general_purpose::STANDARD
1596                .decode(inline_base64)
1597                .into_alien_error()
1598                .context(ErrorData::SerializationFailed {
1599                    message: "Failed to decode inline base64 params for auto-promotion".to_string(),
1600                    data_type: Some("base64".to_string()),
1601                })?;
1602
1603            let raw_len = raw_bytes.len() as u64;
1604            let blob_path = StoragePath::from(format!("arc/commands/{}/params", command_id));
1605
1606            self.storage
1607                .put(&blob_path, Bytes::from(raw_bytes).into())
1608                .await
1609                .into_alien_error()
1610                .context(ErrorData::StorageOperationFailed {
1611                    message: "Failed to auto-promote params to blob storage".to_string(),
1612                    operation: Some("put".to_string()),
1613                    path: Some(blob_path.to_string()),
1614                })?;
1615
1616            debug!(
1617                "Auto-promoted params for command {} to blob ({} bytes raw)",
1618                command_id, raw_len
1619            );
1620
1621            // Store tiny reference in KV instead
1622            let promoted = CommandParamsData {
1623                params: BodySpec::Storage {
1624                    size: Some(raw_len),
1625                    storage_get_request: None,
1626                    storage_put_used: Some(true),
1627                },
1628            };
1629            let promoted_value = serde_json::to_vec(&promoted).into_alien_error().context(
1630                ErrorData::SerializationFailed {
1631                    message: "Failed to serialize promoted params reference".to_string(),
1632                    data_type: Some("CommandParamsData".to_string()),
1633                },
1634            )?;
1635            self.kv.put(&key, promoted_value, None).await.context(
1636                ErrorData::KvOperationFailed {
1637                    operation: "put".to_string(),
1638                    key: key.clone(),
1639                    message: "Failed to store promoted params reference".to_string(),
1640                },
1641            )?;
1642            return Ok(());
1643        }
1644
1645        // Storage references are always tiny, store as-is
1646        self.kv
1647            .put(&key, value, None)
1648            .await
1649            .context(ErrorData::KvOperationFailed {
1650                operation: "put".to_string(),
1651                key: key.clone(),
1652                message: "Failed to store params".to_string(),
1653            })?;
1654        Ok(())
1655    }
1656
1657    pub async fn get_params(&self, command_id: &str) -> Result<Option<BodySpec>> {
1658        let key = format!("cmd:{}:params", command_id);
1659        if let Some(value) = self
1660            .kv
1661            .get(&key)
1662            .await
1663            .context(ErrorData::KvOperationFailed {
1664                operation: "get".to_string(),
1665                key: key.clone(),
1666                message: "Failed to get params".to_string(),
1667            })?
1668        {
1669            let data: CommandParamsData = serde_json::from_slice(&value.value)
1670                .into_alien_error()
1671                .context(ErrorData::SerializationFailed {
1672                message: "Failed to deserialize params".to_string(),
1673                data_type: Some("CommandParamsData".to_string()),
1674            })?;
1675            return Ok(Some(data.params));
1676        }
1677        Ok(None)
1678    }
1679
1680    // --- Response ---
1681
1682    pub async fn store_response(&self, command_id: &str, response: &CommandResponse) -> Result<()> {
1683        let key = format!("cmd:{}:response", command_id);
1684        let data = CommandResponseData {
1685            response: response.clone(),
1686        };
1687        let value = serde_json::to_vec(&data).into_alien_error().context(
1688            ErrorData::SerializationFailed {
1689                message: "Failed to serialize response".to_string(),
1690                data_type: Some("CommandResponseData".to_string()),
1691            },
1692        )?;
1693
1694        // If it fits in KV, store directly (fast path)
1695        if value.len() <= KV_VALUE_THRESHOLD {
1696            self.kv
1697                .put(&key, value, None)
1698                .await
1699                .context(ErrorData::KvOperationFailed {
1700                    operation: "put".to_string(),
1701                    key: key.clone(),
1702                    message: "Failed to store response".to_string(),
1703                })?;
1704            return Ok(());
1705        }
1706
1707        // Auto-promote: inline response exceeds KV limit
1708        if let CommandResponse::Success {
1709            response: BodySpec::Inline { inline_base64 },
1710        } = response
1711        {
1712            let raw_bytes = general_purpose::STANDARD
1713                .decode(inline_base64)
1714                .into_alien_error()
1715                .context(ErrorData::SerializationFailed {
1716                    message: "Failed to decode inline base64 response for auto-promotion"
1717                        .to_string(),
1718                    data_type: Some("base64".to_string()),
1719                })?;
1720
1721            let raw_len = raw_bytes.len() as u64;
1722            let blob_path = StoragePath::from(format!("arc/commands/{}/response", command_id));
1723
1724            self.storage
1725                .put(&blob_path, Bytes::from(raw_bytes).into())
1726                .await
1727                .into_alien_error()
1728                .context(ErrorData::StorageOperationFailed {
1729                    message: "Failed to auto-promote response to blob storage".to_string(),
1730                    operation: Some("put".to_string()),
1731                    path: Some(blob_path.to_string()),
1732                })?;
1733
1734            // Generate presigned GET URL for the caller
1735            let get_request = self
1736                .generate_response_storage_get_request(command_id)
1737                .await?;
1738
1739            debug!(
1740                "Auto-promoted response for command {} to blob ({} bytes raw)",
1741                command_id, raw_len
1742            );
1743
1744            // Store tiny reference in KV
1745            let promoted = CommandResponseData {
1746                response: CommandResponse::Success {
1747                    response: BodySpec::Storage {
1748                        size: Some(raw_len),
1749                        storage_get_request: Some(get_request),
1750                        storage_put_used: Some(true),
1751                    },
1752                },
1753            };
1754            let promoted_value = serde_json::to_vec(&promoted).into_alien_error().context(
1755                ErrorData::SerializationFailed {
1756                    message: "Failed to serialize promoted response reference".to_string(),
1757                    data_type: Some("CommandResponseData".to_string()),
1758                },
1759            )?;
1760            self.kv.put(&key, promoted_value, None).await.context(
1761                ErrorData::KvOperationFailed {
1762                    operation: "put".to_string(),
1763                    key: key.clone(),
1764                    message: "Failed to store promoted response reference".to_string(),
1765                },
1766            )?;
1767            return Ok(());
1768        }
1769
1770        // Error responses or storage references are always small, store as-is
1771        self.kv
1772            .put(&key, value, None)
1773            .await
1774            .context(ErrorData::KvOperationFailed {
1775                operation: "put".to_string(),
1776                key: key.clone(),
1777                message: "Failed to store response".to_string(),
1778            })?;
1779        Ok(())
1780    }
1781
1782    pub async fn get_response(&self, command_id: &str) -> Result<Option<CommandResponse>> {
1783        let key = format!("cmd:{}:response", command_id);
1784        if let Some(value) = self
1785            .kv
1786            .get(&key)
1787            .await
1788            .context(ErrorData::KvOperationFailed {
1789                operation: "get".to_string(),
1790                key: key.clone(),
1791                message: "Failed to get response".to_string(),
1792            })?
1793        {
1794            let data: CommandResponseData = serde_json::from_slice(&value.value)
1795                .into_alien_error()
1796                .context(ErrorData::SerializationFailed {
1797                    message: "Failed to deserialize response".to_string(),
1798                    data_type: Some("CommandResponseData".to_string()),
1799                })?;
1800            return Ok(Some(data.response));
1801        }
1802        Ok(None)
1803    }
1804
1805    // --- Pending Index ---
1806
1807    async fn create_pending_index(
1808        &self,
1809        deployment_id: &str,
1810        target_resource_id: &str,
1811        command_id: &str,
1812    ) -> Result<()> {
1813        // Invariant: the target id is `:`-free (enforced at resolution via
1814        // `validate_command_target_id`), so its prefix `target:{dep}:{rid}:`
1815        // cannot overlap another target's pending keys.
1816        debug_assert!(
1817            !target_resource_id.contains(':'),
1818            "target_resource_id must be ':'-free in the pending index: {target_resource_id}"
1819        );
1820        let timestamp = self.now().timestamp_nanos_opt().unwrap_or(0);
1821        let key = format!(
1822            "target:{}:{}:pending:{}:{}",
1823            deployment_id, target_resource_id, timestamp, command_id
1824        );
1825
1826        // Store empty value - just for ordering
1827        self.kv
1828            .put(&key, vec![], None)
1829            .await
1830            .context(ErrorData::KvOperationFailed {
1831                operation: "put".to_string(),
1832                key: key.clone(),
1833                message: "Failed to create pending index".to_string(),
1834            })?;
1835        Ok(())
1836    }
1837
1838    async fn delete_pending_index(
1839        &self,
1840        deployment_id: &str,
1841        target_resource_id: &str,
1842        command_id: &str,
1843    ) -> Result<()> {
1844        // We need to scan to find the exact key since we don't know the timestamp
1845        let prefix = format!("target:{}:{}:pending:", deployment_id, target_resource_id);
1846        let scan_result = self
1847            .kv
1848            .scan_prefix(&prefix, Some(100), None)
1849            .await
1850            .into_alien_error()
1851            .context(ErrorData::KvOperationFailed {
1852                operation: "scan_prefix".to_string(),
1853                key: prefix.clone(),
1854                message: "Failed to scan pending index".to_string(),
1855            })?;
1856
1857        for entry in scan_result.items {
1858            if entry.key.ends_with(&format!(":{}", command_id)) {
1859                let _ = self.kv.delete(&entry.key, None).await;
1860                break;
1861            }
1862        }
1863        Ok(())
1864    }
1865
1866    // --- Lease ---
1867
1868    async fn delete_lease(&self, command_id: &str) -> Result<()> {
1869        let key = format!("cmd:{}:lease", command_id);
1870        let _ = self.kv.delete(&key, None).await;
1871        Ok(())
1872    }
1873
1874    /// Expire every overdue non-terminal command recorded in the deadline
1875    /// index. Intended to run periodically from the hosting process.
1876    ///
1877    /// Deadlines are otherwise only enforced lazily (status polls and lease
1878    /// scans), which never reaches a command nobody polls — most notably a
1879    /// `PendingUpload` whose params upload never completed, which has no
1880    /// pending-index entry and would otherwise live forever.
1881    ///
1882    /// Uses the conditional terminal transition, so racing a concurrent
1883    /// submit is safe: whoever wins, the record stays consistent. Returns
1884    /// the number of commands expired.
1885    pub async fn reap_expired_commands(&self) -> Result<u32> {
1886        let now = self.now();
1887        let mut expired = 0u32;
1888        let mut cursor: Option<String> = None;
1889        // Paginate the whole index (bounded page count as a runaway guard):
1890        // keys are not numerically ordered — the timestamp segment isn't
1891        // zero-padded — so due entries can sit behind any number of
1892        // future-dated ones and a single capped scan would starve them.
1893        for _ in 0..64 {
1894            let scan = self
1895                .kv
1896                .scan_prefix("deadline:", Some(256), cursor.clone())
1897                .await
1898                .into_alien_error()
1899                .context(ErrorData::KvOperationFailed {
1900                    operation: "scan_prefix".to_string(),
1901                    key: "deadline:".to_string(),
1902                    message: "Failed to scan the deadline index".to_string(),
1903                })?;
1904            let next_cursor = scan.next_cursor.clone();
1905            for entry in scan.items {
1906                let Ok(data) = serde_json::from_slice::<DeadlineIndexData>(&entry.value) else {
1907                    warn!(key = %entry.key, "Unparseable deadline index entry; deleting");
1908                    let _ = self.kv.delete(&entry.key, None).await;
1909                    continue;
1910                };
1911                if data.deadline > now {
1912                    // Not due yet. (Keys are not sortable numerically — the
1913                    // timestamp segment isn't zero-padded — so keep scanning.)
1914                    continue;
1915                }
1916
1917                let status = self
1918                    .command_registry
1919                    .get_command_status(&data.command_id)
1920                    .await?;
1921                match status {
1922                    None => {
1923                        let _ = self.kv.delete(&entry.key, None).await;
1924                    }
1925                    Some(status) if status.state.is_terminal() => {
1926                        let _ = self.kv.delete(&entry.key, None).await;
1927                    }
1928                    Some(status) => {
1929                        let won = self
1930                        .command_registry
1931                        .complete_command(
1932                            &data.command_id,
1933                            CommandState::Expired,
1934                            now,
1935                            None,
1936                            Some(serde_json::json!({
1937                                "code": "COMMAND_EXPIRED",
1938                                "message": format!("Deadline {} elapsed", data.deadline.to_rfc3339()),
1939                            })),
1940                        )
1941                        .await?;
1942                        if won {
1943                            expired += 1;
1944                            info!(command_id = %data.command_id, "Expired overdue command");
1945                            let _ = self.delete_lease(&data.command_id).await;
1946                            let _ = self
1947                                .delete_pending_index(
1948                                    &status.deployment_id,
1949                                    &status.target.resource_id,
1950                                    &data.command_id,
1951                                )
1952                                .await;
1953                        }
1954                        let _ = self.kv.delete(&entry.key, None).await;
1955                    }
1956                }
1957            }
1958            match next_cursor {
1959                Some(next) => cursor = Some(next),
1960                None => break,
1961            }
1962        }
1963        Ok(expired)
1964    }
1965
1966    // --- Deadline Index ---
1967
1968    async fn create_deadline_index(&self, command_id: &str, deadline: DateTime<Utc>) -> Result<()> {
1969        let key = format!(
1970            "deadline:{}:{}",
1971            deadline.timestamp_nanos_opt().unwrap_or(0),
1972            command_id
1973        );
1974
1975        let data = DeadlineIndexData {
1976            command_id: command_id.to_string(),
1977            deadline,
1978        };
1979        let value = serde_json::to_vec(&data).into_alien_error().context(
1980            ErrorData::SerializationFailed {
1981                message: "Failed to serialize deadline index".to_string(),
1982                data_type: Some("DeadlineIndexData".to_string()),
1983            },
1984        )?;
1985
1986        // The entry must remain VISIBLE well past the deadline: scan_prefix
1987        // treats logically-expired keys as absent on every provider, so a
1988        // TTL equal to the deadline would hide the entry at exactly the
1989        // moment the reaper needs it (the bug that made the reaper inert).
1990        // The reaper deletes entries as it processes them; the 7-day grace
1991        // is only self-cleaning for processes that never run a reaper.
1992        const DEADLINE_INDEX_GRACE: chrono::Duration = chrono::Duration::days(7);
1993        let ttl = deadline
1994            .signed_duration_since(self.now())
1995            .checked_add(&DEADLINE_INDEX_GRACE)
1996            .unwrap_or(DEADLINE_INDEX_GRACE);
1997        let options = (ttl.num_seconds() > 0).then(|| PutOptions {
1998            ttl: Some(Duration::from_secs(ttl.num_seconds() as u64)),
1999            condition: PutCondition::None,
2000        });
2001
2002        self.kv
2003            .put(&key, value, options)
2004            .await
2005            .context(ErrorData::KvOperationFailed {
2006                operation: "put".to_string(),
2007                key: key.clone(),
2008                message: "Failed to create deadline index".to_string(),
2009            })?;
2010        Ok(())
2011    }
2012
2013    // --- Dispatch ---
2014
2015    async fn dispatch_command_push(
2016        &self,
2017        command_id: &str,
2018        deployment_id: &str,
2019    ) -> Result<CommandState> {
2020        // Get metadata from registry
2021        let metadata = self
2022            .command_registry
2023            .get_command_metadata(command_id)
2024            .await?
2025            .ok_or_else(|| {
2026                AlienError::new(ErrorData::CommandNotFound {
2027                    command_id: command_id.to_string(),
2028                })
2029            })?;
2030
2031        // Get params from KV
2032        let params = self.get_params(command_id).await?.ok_or_else(|| {
2033            AlienError::new(ErrorData::CommandNotFound {
2034                command_id: command_id.to_string(),
2035            })
2036        })?;
2037
2038        // Build envelope
2039        let envelope = self
2040            .build_envelope(command_id, &metadata, params, None, None, None)
2041            .await?;
2042
2043        // Mark Dispatched BEFORE invoking the transport: a fast worker can
2044        // execute and submit before this function resumes, and submit
2045        // validates state == Dispatched — the old dispatch-then-mark order
2046        // could reject that submit (losing the response) or stomp its
2047        // terminal state back to Dispatched.
2048        if !self
2049            .command_registry
2050            .mark_dispatched_if_not_terminal(command_id, self.now())
2051            .await?
2052        {
2053            return Ok(self
2054                .command_registry
2055                .get_command_status(command_id)
2056                .await?
2057                .map(|status| status.state)
2058                .unwrap_or(CommandState::Dispatched));
2059        }
2060
2061        // A definite pre-delivery rejection (connection refusal, request
2062        // builder failure, or any HTTP status other than the runtime's exact
2063        // 202 acceptance) is safe to record as terminal DELIVERY_FAILED.
2064        // Other transport errors are ambiguous: the target may have accepted
2065        // the envelope before the response was lost. Keep those Dispatched so
2066        // a late response remains valid and return the durable ID for polling;
2067        // reverting/retrying could execute the command twice.
2068        if let Err(error) = self.command_dispatcher.dispatch(&envelope).await {
2069            if is_definite_dispatch_rejection(&error) {
2070                let delivery_failure = CommandResponse::error(
2071                    "DELIVERY_FAILED",
2072                    "Worker runtime did not accept command delivery",
2073                );
2074                self.submit_command_response(command_id, delivery_failure)
2075                    .await?;
2076                warn!(
2077                    command_id,
2078                    deployment_id,
2079                    error = %error,
2080                    "Push dispatch was definitely rejected; command marked Failed"
2081                );
2082                return Ok(CommandState::Failed);
2083            }
2084
2085            let error = error.context(ErrorData::TransportDispatchFailed {
2086                message: "Failed to dispatch command".to_string(),
2087                transport_type: None,
2088                target: Some(deployment_id.to_string()),
2089            });
2090            warn!(
2091                command_id,
2092                deployment_id,
2093                error = %error,
2094                "Push dispatch acknowledgement failed; command remains Dispatched for a possible late response"
2095            );
2096            return Ok(CommandState::Dispatched);
2097        }
2098
2099        info!("Command {} dispatched via push", envelope.command_id);
2100        Ok(CommandState::Dispatched)
2101    }
2102
2103    async fn build_envelope(
2104        &self,
2105        command_id: &str,
2106        metadata: &CommandEnvelopeData,
2107        mut params: BodySpec,
2108        authority_deadline: Option<DateTime<Utc>>,
2109        response_deadline: Option<DateTime<Utc>>,
2110        lease_id: Option<&str>,
2111    ) -> Result<Envelope> {
2112        // The result credentials follow the command's execution window
2113        // (`response_deadline`), not the receiver credential that leased it.
2114        // A leased command's response URL names its lease.
2115        let response_handling = self
2116            .create_response_handling(command_id, response_deadline, lease_id)
2117            .await?;
2118
2119        // Re-inline: if params are in blob but fit in transport limit, read and embed inline.
2120        // This avoids unnecessary storage downloads for medium-sized params (18KB–150KB).
2121        if let BodySpec::Storage { size, .. } = &params {
2122            let raw_size = size.unwrap_or(0) as usize;
2123            if raw_size > 0 && raw_size <= self.inline_max_bytes {
2124                let blob_path = StoragePath::from(format!("arc/commands/{}/params", command_id));
2125                match self.storage.get(&blob_path).await {
2126                    Ok(get_result) => match get_result.bytes().await {
2127                        Ok(raw_bytes) => {
2128                            params = BodySpec::inline(&raw_bytes);
2129                            debug!(
2130                                "Re-inlined params for command {} ({} bytes) into envelope",
2131                                command_id, raw_size
2132                            );
2133                        }
2134                        Err(e) => {
2135                            debug!(
2136                                    "Failed to read blob bytes for re-inline (command {}), falling back to presigned URL: {}",
2137                                    command_id, e
2138                                );
2139                        }
2140                    },
2141                    Err(e) => {
2142                        debug!(
2143                            "Failed to read blob for re-inline (command {}), falling back to presigned URL: {}",
2144                            command_id, e
2145                        );
2146                    }
2147                }
2148            }
2149        }
2150
2151        // If params are still Storage (either too large or re-inline failed),
2152        // always mint a fresh GET request. A command may remain Pending longer
2153        // than the URL minted at upload completion, and leasing must never hand
2154        // a Worker an already-expired storage credential.
2155        if let BodySpec::Storage {
2156            size,
2157            storage_get_request: _,
2158            storage_put_used,
2159        } = &params
2160        {
2161            let get_request = self
2162                .generate_storage_get_request_with_deadline(command_id, authority_deadline)
2163                .await?;
2164            params = BodySpec::Storage {
2165                size: *size,
2166                storage_get_request: Some(get_request),
2167                storage_put_used: *storage_put_used,
2168            };
2169        }
2170
2171        Ok(Envelope::new(
2172            metadata.deployment_id.clone(),
2173            metadata.target.clone(),
2174            command_id.to_string(),
2175            metadata.attempt,
2176            metadata.deadline,
2177            metadata.command.clone(),
2178            params,
2179            response_handling,
2180        ))
2181    }
2182
2183    /// Refresh response credentials after the caller has authorized the exact
2184    /// command target. A running command may outlast its original credential.
2185    pub async fn refresh_response_handling(
2186        &self,
2187        command_id: &str,
2188        lease_id: &str,
2189        authority_deadline: Option<DateTime<Utc>>,
2190    ) -> Result<ResponseHandling> {
2191        let command = self
2192            .command_registry
2193            .get_command_metadata(command_id)
2194            .await?
2195            .ok_or_else(|| {
2196                AlienError::new(ErrorData::CommandNotFound {
2197                    command_id: command_id.into(),
2198                })
2199            })?;
2200        if command.state != CommandState::Dispatched {
2201            return Err(AlienError::new(ErrorData::InvalidCommand {
2202                message: "Response credentials require a dispatched command".into(),
2203            }));
2204        }
2205        let key = format!("cmd:{command_id}:lease");
2206        let entry = self
2207            .kv
2208            .get(&key)
2209            .await
2210            .context(ErrorData::KvOperationFailed {
2211                operation: "get".into(),
2212                key: key.clone(),
2213                message: "Failed to read response lease".into(),
2214            })?
2215            .ok_or_else(|| {
2216                AlienError::new(ErrorData::LeaseNotFound {
2217                    lease_id: lease_id.into(),
2218                })
2219            })?;
2220        let lease: LeaseData = serde_json::from_slice(&entry.value)
2221            .into_alien_error()
2222            .context(ErrorData::SerializationFailed {
2223                message: "Failed to decode response lease".into(),
2224                data_type: Some("LeaseData".into()),
2225            })?;
2226        if lease.lease_id != lease_id
2227            || lease.owner != command.deployment_id
2228            || lease.expires_at <= self.now()
2229        {
2230            return Err(AlienError::new(ErrorData::LeaseNotFound {
2231                lease_id: lease_id.into(),
2232            }));
2233        }
2234        let deadline =
2235            authority_deadline.map_or(lease.expires_at, |deadline| deadline.min(lease.expires_at));
2236        let handling = self
2237            .create_response_handling(command_id, Some(deadline), Some(lease_id))
2238            .await?;
2239        let current = self
2240            .kv
2241            .get(&key)
2242            .await
2243            .context(ErrorData::KvOperationFailed {
2244                operation: "get".into(),
2245                key,
2246                message: "Failed to recheck response lease".into(),
2247            })?;
2248        if self.now() >= deadline || current.is_none_or(|current| current.version != entry.version)
2249        {
2250            return Err(AlienError::new(ErrorData::LeaseNotFound {
2251                lease_id: lease_id.into(),
2252            }));
2253        }
2254        Ok(handling)
2255    }
2256
2257    async fn create_response_handling(
2258        &self,
2259        command_id: &str,
2260        authority_deadline: Option<DateTime<Utc>>,
2261        lease_id: Option<&str>,
2262    ) -> Result<ResponseHandling> {
2263        let upload_path = StoragePath::from(format!("arc/commands/{}/response", command_id));
2264        let default_deadline =
2265            self.now() + chrono::Duration::seconds(Self::RESPONSE_CREDENTIAL_LIFETIME_SECS as i64);
2266        let deadline =
2267            authority_deadline.map_or(default_deadline, |deadline| deadline.min(default_deadline));
2268        let expires_in = self.remaining_authority(deadline)?;
2269        let presigned = self
2270            .storage
2271            .presigned_put(&upload_path, expires_in)
2272            .await
2273            .context(ErrorData::StorageOperationFailed {
2274                message: "Failed to create response upload URL".to_string(),
2275                operation: Some("presigned_put".to_string()),
2276                path: Some(upload_path.to_string()),
2277            })?;
2278
2279        self.check_storage_deadline(&presigned, deadline)?;
2280        let (response_token, expires) = self.sign_response_url(command_id, lease_id, deadline);
2281
2282        Ok(ResponseHandling {
2283            max_inline_bytes: self.inline_max_bytes as u64,
2284            submit_response_url: format!(
2285                "{}/commands/{}/response?response_token={}&expires={}{}",
2286                self.base_url.trim_end_matches('/'),
2287                command_id,
2288                response_token,
2289                expires,
2290                lease_id
2291                    .map(|lease_id| format!("&lease_id={lease_id}"))
2292                    .unwrap_or_default(),
2293            ),
2294            storage_upload_request: presigned,
2295        })
2296    }
2297
2298    async fn generate_params_upload(&self, command_id: &str) -> Result<StorageUpload> {
2299        let upload_path = StoragePath::from(format!("arc/commands/{}/params", command_id));
2300        let expires_in = Duration::from_secs(3600);
2301        let presigned = self
2302            .storage
2303            .presigned_put(&upload_path, expires_in)
2304            .await
2305            .into_alien_error()
2306            .context(ErrorData::StorageOperationFailed {
2307                message: "Failed to create presigned URL".to_string(),
2308                operation: Some("presigned_put".to_string()),
2309                path: Some(upload_path.to_string()),
2310            })?;
2311
2312        Ok(StorageUpload {
2313            put_request: presigned.clone(),
2314            expires_at: presigned.expiration,
2315        })
2316    }
2317
2318    async fn generate_storage_get_request(&self, command_id: &str) -> Result<PresignedRequest> {
2319        self.generate_storage_get_request_with_deadline(command_id, None)
2320            .await
2321    }
2322
2323    async fn generate_storage_get_request_with_deadline(
2324        &self,
2325        command_id: &str,
2326        authority_deadline: Option<DateTime<Utc>>,
2327    ) -> Result<PresignedRequest> {
2328        let path = StoragePath::from(format!("arc/commands/{}/params", command_id));
2329        let default_deadline = self.now() + chrono::Duration::hours(1);
2330        let deadline =
2331            authority_deadline.map_or(default_deadline, |deadline| deadline.min(default_deadline));
2332        let expires_in = self.remaining_authority(deadline)?;
2333        let request = self
2334            .storage
2335            .presigned_get(&path, expires_in)
2336            .await
2337            .context(ErrorData::StorageOperationFailed {
2338                message: "Failed to create storage get request".to_string(),
2339                operation: Some("presigned_get".to_string()),
2340                path: Some(path.to_string()),
2341            })?;
2342        self.check_storage_deadline(&request, deadline)?;
2343        Ok(request)
2344    }
2345
2346    async fn generate_response_storage_get_request(
2347        &self,
2348        command_id: &str,
2349    ) -> Result<PresignedRequest> {
2350        let path = StoragePath::from(format!("arc/commands/{}/response", command_id));
2351        let expires_in = Duration::from_secs(3600);
2352        self.storage.presigned_get(&path, expires_in).await.context(
2353            ErrorData::StorageOperationFailed {
2354                message: "Failed to create response storage get request".to_string(),
2355                operation: Some("presigned_get".to_string()),
2356                path: Some(path.to_string()),
2357            },
2358        )
2359    }
2360
2361    fn extract_command_id_from_index_key(&self, index_key: &str) -> Result<String> {
2362        index_key
2363            .split(':')
2364            .last()
2365            .ok_or_else(|| {
2366                AlienError::new(ErrorData::Other {
2367                    message: format!("Invalid index key format: {}", index_key),
2368                })
2369            })
2370            .map(|s| s.to_string())
2371    }
2372}
2373
2374fn validate_operation_result_contract_request(
2375    command: &str,
2376    contract_present: bool,
2377    registry_supports_contract: bool,
2378) -> Result<()> {
2379    let operation_command = command.strip_prefix("operation/v1/").is_some_and(|digest| {
2380        digest.len() == 64
2381            && digest
2382                .bytes()
2383                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
2384    });
2385    if operation_command && !contract_present {
2386        return Err(AlienError::new(ErrorData::InvalidCommand {
2387            message: "Version-qualified operation commands require an immutable result contract"
2388                .to_string(),
2389        }));
2390    }
2391    if contract_present && (!operation_command || !registry_supports_contract) {
2392        return Err(AlienError::new(ErrorData::InvalidCommand {
2393            message:
2394                "This command registry cannot persist the operation result contract before dispatch"
2395                    .to_string(),
2396        }));
2397    }
2398    Ok(())
2399}
2400
2401#[cfg(test)]
2402mod relative_url_tests {
2403    use super::*;
2404    use alien_core::presigned::PresignedOperation;
2405    use std::collections::HashMap;
2406
2407    fn http_request(url: &str, operation: PresignedOperation) -> PresignedRequest {
2408        PresignedRequest::new_http(
2409            url.to_string(),
2410            match operation {
2411                PresignedOperation::Get => "GET",
2412                PresignedOperation::Put => "PUT",
2413                PresignedOperation::Delete => "DELETE",
2414            }
2415            .to_string(),
2416            HashMap::new(),
2417            operation,
2418            "commands/test".to_string(),
2419            Utc::now() + chrono::Duration::minutes(5),
2420        )
2421    }
2422
2423    #[test]
2424    fn leased_manager_urls_are_relative_to_lease_endpoint() {
2425        let mut envelope = Envelope::new(
2426            "deployment",
2427            CommandTarget::new("daemon", CommandTargetType::Daemon),
2428            "command",
2429            1,
2430            None,
2431            "run",
2432            BodySpec::Storage {
2433                size: Some(2048),
2434                storage_get_request: Some(http_request(
2435                    "http://manager.internal/storage/params?signature=params",
2436                    PresignedOperation::Get,
2437                )),
2438                storage_put_used: Some(true),
2439            },
2440            ResponseHandling {
2441                max_inline_bytes: 1024,
2442                submit_response_url:
2443                    "http://manager.internal/v1/commands/command/response?response_token=DoNotCanonicalize%2FValue&expires=1"
2444                        .to_string(),
2445                storage_upload_request: http_request(
2446                    "http://manager.internal/v1/storage/response?signature=DoNotCanonicalize%2FUpload",
2447                    PresignedOperation::Put,
2448                ),
2449            },
2450        );
2451
2452        CommandServer::relativize_manager_urls(&mut envelope, "http://manager.internal/v1");
2453
2454        assert_eq!(
2455            envelope.response_handling.submit_response_url,
2456            "command/response?response_token=DoNotCanonicalize%2FValue&expires=1"
2457        );
2458        assert_eq!(
2459            envelope.response_handling.storage_upload_request.url(),
2460            "../storage/response?signature=DoNotCanonicalize%2FUpload"
2461        );
2462        let BodySpec::Storage {
2463            storage_get_request: Some(params),
2464            ..
2465        } = &envelope.params
2466        else {
2467            panic!("storage params request");
2468        };
2469        assert_eq!(params.url(), "../../storage/params?signature=params");
2470
2471        envelope.response_handling.storage_upload_request = http_request(
2472            "https://storage.example.com/result?signature=cloud",
2473            PresignedOperation::Put,
2474        );
2475        CommandServer::relativize_manager_urls(&mut envelope, "http://manager.internal/v1");
2476        assert_eq!(
2477            envelope.response_handling.storage_upload_request.url(),
2478            "https://storage.example.com/result?signature=cloud",
2479            "cloud-presigned URLs must remain byte-for-byte absolute"
2480        );
2481    }
2482}
2483
2484#[cfg(test)]
2485mod idempotency_key_tests {
2486    use super::*;
2487    use crate::server::{validate_command_name, validate_command_target_id};
2488
2489    #[test]
2490    fn storage_key_preserves_portable_legacy_keys_and_encodes_versioned_commands() {
2491        let legacy = CommandServer::compose_idempotency_key("dep", "operator", "refresh", "retry");
2492        assert_eq!(
2493            CommandServer::storage_idempotency_key(&legacy),
2494            "idem:dep:operator:refresh:retry"
2495        );
2496
2497        let versioned =
2498            CommandServer::compose_idempotency_key("dep", "operator", "operation/v1/abc", "retry");
2499        let encoded = CommandServer::storage_idempotency_key(&versioned);
2500        assert!(encoded.starts_with("idem2:"));
2501        assert!(validate_key(&encoded).is_ok());
2502        assert_eq!(encoded, CommandServer::storage_idempotency_key(&versioned));
2503        assert_ne!(
2504            encoded,
2505            CommandServer::storage_idempotency_key(&CommandServer::compose_idempotency_key(
2506                "dep",
2507                "operator",
2508                "operation/v1/def",
2509                "retry",
2510            )),
2511        );
2512    }
2513
2514    #[test]
2515    fn definite_dispatch_rejection_is_classified_by_typed_error_data() {
2516        let rejected = AlienError::new(ErrorData::TransportDispatchRejected {
2517            message: "not accepted".to_string(),
2518            transport_type: Some("http".to_string()),
2519            target: Some("command-id".to_string()),
2520        });
2521        assert!(is_definite_dispatch_rejection(&rejected));
2522
2523        let ambiguous = AlienError::new(ErrorData::TransportDispatchFailed {
2524            message: "acknowledgement lost".to_string(),
2525            transport_type: Some("http".to_string()),
2526            target: Some("command-id".to_string()),
2527        });
2528        assert!(!is_definite_dispatch_rejection(&ambiguous));
2529    }
2530
2531    /// Idempotency keys are `{dep}:{rid}:{command}:{key}`. If a target id could
2532    /// contain ':', the `rid` segment would be ambiguous: the two triples
2533    ///   (rid="svc",   command="a:b", key="k")
2534    ///   (rid="svc:a", command="b",   key="k")
2535    /// both compose to `dep:svc:a:b:k`. The shared guard forbids ':' in a target
2536    /// id, so the second can never be a resolved target — closing the collision
2537    /// at the rid boundary. Only the colon-free composition is exercised here;
2538    /// the colliding one is proven unreachable via the guard.
2539    #[test]
2540    fn target_id_colon_guard_prevents_idempotency_key_collision() {
2541        let colliding = CommandServer::compose_idempotency_key("dep", "svc", "a:b", "k");
2542        assert_eq!(colliding, "dep:svc:a:b:k");
2543
2544        // The alternate triple that would collide needs target id "svc:a".
2545        assert!(
2546            validate_command_target_id("svc:a").is_err(),
2547            "a ':'-bearing target id must be rejected so it cannot forge the rid segment"
2548        );
2549        assert!(validate_command_target_id("svc").is_ok());
2550    }
2551
2552    /// The command name is the other forgeable segment. Client keys routinely
2553    /// contain ':', so without a command-name guard these two distinct inputs
2554    ///   (command="a:b", key="c")
2555    ///   (command="a",   key="b:c")
2556    /// both compose to `dep:svc:a:b:c` — a cross-command idempotency collision.
2557    /// The guard rejects the ':'-bearing command name, so only the second input
2558    /// is ever composed; the first can never reach key composition.
2559    #[test]
2560    fn command_name_colon_guard_prevents_idempotency_key_collision() {
2561        // Without the guard, both inputs compose to the identical string.
2562        let forged = CommandServer::compose_idempotency_key("dep", "svc", "a:b", "c");
2563        let legitimate = CommandServer::compose_idempotency_key("dep", "svc", "a", "b:c");
2564        assert_eq!(
2565            forged, legitimate,
2566            "these inputs are exactly the colliding pair the guard must separate"
2567        );
2568        assert_eq!(legitimate, "dep:svc:a:b:c");
2569
2570        // The guard makes the colliding input unreachable: a ':'-bearing command
2571        // name is rejected, while the legitimate command name is accepted. With
2572        // the forger blocked, `a:b`+`c` can never compose the shared key — only
2573        // the distinct `a`+`b:c` command can.
2574        let err = validate_command_name("a:b").expect_err("':'-bearing command must be rejected");
2575        assert_eq!(err.code, "INVALID_COMMAND");
2576        assert!(validate_command_name("a").is_ok());
2577    }
2578
2579    #[test]
2580    fn versioned_operation_requires_atomic_result_contract_support() {
2581        let command = format!("operation/v1/{}", "a".repeat(64));
2582
2583        assert!(validate_operation_result_contract_request(&command, true, true).is_ok());
2584        assert!(validate_operation_result_contract_request(&command, false, true).is_err());
2585        assert!(validate_operation_result_contract_request(&command, true, false).is_err());
2586        assert!(validate_operation_result_contract_request("postgres/health", true, true).is_err());
2587    }
2588}