1use 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
30const KV_VALUE_THRESHOLD: usize = 20_000;
33
34fn is_definite_dispatch_rejection(error: &crate::error::Error) -> bool {
35 matches!(
36 error.error.as_ref(),
37 Some(ErrorData::TransportDispatchRejected { .. })
38 )
39}
40
41pub mod axum_handlers;
42pub mod command_registry;
43pub mod storage;
44
45pub use crate::dispatchers::{CommandDispatcher, NullCommandDispatcher};
46pub use axum_handlers::{
47 create_axum_router, CommandPayloadResponse, HasCommandServer, StorePayloadRequest,
48};
49pub use command_registry::{
50 delivery_mode_for, select_command_target, validate_command_name, validate_command_target_id,
51 CommandAccessContext, CommandEnvelopeData, CommandMetadata, CommandRegistry, CommandStatus,
52 InMemoryCommandRegistry, ResolvedCommandTarget,
53};
54
55#[derive(Debug, Clone, Serialize, Deserialize)]
61struct CommandParamsData {
62 pub params: BodySpec,
63}
64
65#[derive(Debug, Clone, Serialize, Deserialize)]
67struct CommandResponseData {
68 pub response: CommandResponse,
69}
70
71#[derive(Debug, Clone, Serialize, Deserialize)]
73struct LeaseData {
74 pub lease_id: String,
75 pub acquired_at: DateTime<Utc>,
76 pub expires_at: DateTime<Utc>,
77 pub owner: String,
78}
79
80#[derive(Debug, Clone, Serialize, Deserialize)]
82struct DeadlineIndexData {
83 pub command_id: String,
84 pub deadline: DateTime<Utc>,
85}
86
87pub struct CommandServer {
96 kv: Arc<dyn Kv>,
97 storage: Arc<dyn Storage>,
98 command_dispatcher: Arc<dyn CommandDispatcher>,
99 command_registry: Arc<dyn CommandRegistry>,
100 inline_max_bytes: usize,
101 base_url: String,
102 response_signing_key: Vec<u8>,
103}
104
105impl CommandServer {
106 pub fn persists_operation_result_contract(&self) -> bool {
109 self.command_registry.persists_operation_result_contract()
110 }
111
112 pub fn new(
114 kv: Arc<dyn Kv>,
115 storage: Arc<dyn Storage>,
116 command_dispatcher: Arc<dyn CommandDispatcher>,
117 command_registry: Arc<dyn CommandRegistry>,
118 base_url: String,
119 response_signing_key: Vec<u8>,
120 ) -> Self {
121 Self {
122 kv,
123 storage,
124 command_dispatcher,
125 command_registry,
126 inline_max_bytes: INLINE_MAX_BYTES,
127 base_url,
128 response_signing_key,
129 }
130 }
131
132 pub fn with_inline_limit(
134 kv: Arc<dyn Kv>,
135 storage: Arc<dyn Storage>,
136 command_dispatcher: Arc<dyn CommandDispatcher>,
137 command_registry: Arc<dyn CommandRegistry>,
138 base_url: String,
139 inline_max_bytes: usize,
140 response_signing_key: Vec<u8>,
141 ) -> Self {
142 Self {
143 kv,
144 storage,
145 command_dispatcher,
146 command_registry,
147 inline_max_bytes,
148 base_url,
149 response_signing_key,
150 }
151 }
152
153 const MAX_RESPONSE_TOKEN_LIFETIME_SECS: i64 = 7200;
155 const RESPONSE_CREDENTIAL_LIFETIME_SECS: u64 = 7200;
159
160 fn sign_response_url(&self, command_id: &str) -> (String, i64) {
165 let expires = Utc::now().timestamp() + Self::RESPONSE_CREDENTIAL_LIFETIME_SECS as i64;
166 let message = format!("commands.v1:{}:{}", command_id, expires);
167
168 type HmacSha256 = Hmac<Sha256>;
169 let mut mac =
170 HmacSha256::new_from_slice(&self.response_signing_key).expect("HMAC accepts any key");
171 mac.update(message.as_bytes());
172 let result = mac.finalize();
173 let token = hex::encode(result.into_bytes());
174
175 (token, expires)
176 }
177
178 pub fn verify_response_token(&self, command_id: &str, token: &str, expires: i64) -> bool {
183 if token.len() != 64 {
185 return false;
186 }
187
188 let message = format!("commands.v1:{}:{}", command_id, expires);
189
190 type HmacSha256 = Hmac<Sha256>;
191 let mut mac =
192 HmacSha256::new_from_slice(&self.response_signing_key).expect("HMAC accepts any key");
193 mac.update(message.as_bytes());
194
195 let Ok(token_bytes) = hex::decode(token) else {
197 return false;
198 };
199 let hmac_valid = mac.verify_slice(&token_bytes).is_ok();
200
201 let now = Utc::now().timestamp();
203 let not_expired = now <= expires;
204 let within_max_lifetime = expires <= now + Self::MAX_RESPONSE_TOKEN_LIFETIME_SECS;
205
206 hmac_valid && not_expired && within_max_lifetime
207 }
208
209 pub async fn create_command(
221 &self,
222 request: CreateCommandRequest,
223 ) -> Result<CreateCommandResponse> {
224 self.validate_create_command(&request).await?;
226
227 let resolved_target = self
230 .command_registry
231 .resolve_target(
232 &request.deployment_id,
233 &request.command,
234 request.target_resource_id.as_deref(),
235 )
236 .await?;
237
238 let composed_idempotency_key = request.idempotency_key.as_ref().map(|idem_key| {
245 Self::compose_idempotency_key(
246 &request.deployment_id,
247 &resolved_target.target.resource_id,
248 &request.command,
249 idem_key,
250 )
251 });
252
253 if let Some(ref composed_key) = composed_idempotency_key {
255 if let Some(existing_id) = self.check_idempotency(composed_key).await? {
256 let status = self
258 .command_registry
259 .get_command_status(&existing_id)
260 .await?;
261 if let Some(s) = status {
262 return Ok(CreateCommandResponse {
263 command_id: existing_id,
264 created: false,
265 state: s.state,
266 storage_upload: None,
267 inline_allowed_up_to: self.inline_max_bytes as u64,
268 next: "poll".to_string(),
269 });
270 }
271 }
272 }
273
274 let (initial_state, request_size_bytes) = match &request.params {
276 BodySpec::Inline { inline_base64 } => {
277 let size = inline_base64.len() as u64;
278 (CommandState::Pending, Some(size))
279 }
280 BodySpec::Storage { size, .. } => {
281 if size.unwrap_or(0) > self.inline_max_bytes as u64 {
282 (CommandState::PendingUpload, *size)
283 } else {
284 (CommandState::Pending, *size)
285 }
286 }
287 };
288
289 let metadata = self
291 .command_registry
292 .create_command(
293 &request.deployment_id,
294 &request.command,
295 &resolved_target,
296 initial_state,
297 request.deadline,
298 request_size_bytes,
299 request.operation_result_contract.clone(),
300 )
301 .await?;
302
303 let command_id = metadata.command_id;
304 let delivery_mode = metadata.delivery_mode;
305
306 if let Some(ref composed_key) = composed_idempotency_key {
313 if let Some(winner_id) = self.store_idempotency(composed_key, &command_id).await? {
314 let _ = self
315 .command_registry
316 .complete_command(
317 &command_id,
318 CommandState::Failed,
319 Utc::now(),
320 None,
321 Some(serde_json::json!({
322 "code": "IDEMPOTENT_DUPLICATE",
323 "message": format!(
324 "Superseded by concurrent create '{}' with the same idempotency key",
325 winner_id
326 ),
327 })),
328 )
329 .await?;
330 let status = self.command_registry.get_command_status(&winner_id).await?;
331 let state = status.map(|s| s.state).unwrap_or(CommandState::Pending);
332 return Ok(CreateCommandResponse {
333 command_id: winner_id,
334 created: false,
335 state,
336 storage_upload: None,
337 inline_allowed_up_to: self.inline_max_bytes as u64,
338 next: "poll".to_string(),
339 });
340 }
341 }
342
343 self.store_params(&command_id, &request.params).await?;
345
346 let storage_upload = if initial_state == CommandState::PendingUpload {
348 Some(self.generate_params_upload(&command_id).await?)
349 } else {
350 None
351 };
352
353 let (final_state, next_action) = if initial_state == CommandState::Pending {
355 match delivery_mode {
356 CommandDeliveryMode::Push => {
357 let state = self
359 .dispatch_command_push(&command_id, &request.deployment_id)
360 .await?;
361 (state, "poll")
362 }
363 CommandDeliveryMode::Pull => {
364 self.create_pending_index(
367 &request.deployment_id,
368 &metadata.target.resource_id,
369 &command_id,
370 )
371 .await?;
372 debug!("Command {} ready for target-scoped lease", command_id);
373 (CommandState::Pending, "poll")
374 }
375 }
376 } else {
377 (initial_state, "upload")
379 };
380
381 if let Some(deadline) = request.deadline {
383 self.create_deadline_index(&command_id, deadline).await?;
384 }
385
386 Ok(CreateCommandResponse {
387 command_id,
388 created: true,
389 state: final_state,
390 storage_upload,
391 inline_allowed_up_to: self.inline_max_bytes as u64,
392 next: next_action.to_string(),
393 })
394 }
395
396 pub async fn upload_complete(
398 &self,
399 command_id: &str,
400 upload_request: UploadCompleteRequest,
401 ) -> Result<UploadCompleteResponse> {
402 let status = self
404 .command_registry
405 .get_command_status(command_id)
406 .await?
407 .ok_or_else(|| {
408 AlienError::new(ErrorData::CommandNotFound {
409 command_id: command_id.to_string(),
410 })
411 })?;
412
413 if status.state != CommandState::PendingUpload {
415 return Err(AlienError::new(ErrorData::InvalidStateTransition {
416 from: status.state.as_ref().to_string(),
417 to: CommandState::Pending.as_ref().to_string(),
418 }));
419 }
420
421 let storage_get_request = self.generate_storage_get_request(command_id).await?;
423 let params = BodySpec::Storage {
424 size: Some(upload_request.size),
425 storage_get_request: Some(storage_get_request),
426 storage_put_used: None,
427 };
428 self.store_params(command_id, ¶ms).await?;
429
430 let transitioned = self
432 .command_registry
433 .update_command_state(command_id, CommandState::Pending, None, None, None, None)
434 .await?;
435 if !transitioned {
436 let current_state = self
437 .command_registry
438 .get_command_status(command_id)
439 .await?
440 .map(|current| current.state)
441 .unwrap_or(status.state);
442 return Err(AlienError::new(ErrorData::InvalidStateTransition {
443 from: current_state.as_ref().to_string(),
444 to: CommandState::Pending.as_ref().to_string(),
445 }));
446 }
447
448 let metadata = self
450 .command_registry
451 .get_command_metadata(command_id)
452 .await?
453 .ok_or_else(|| {
454 AlienError::new(ErrorData::CommandNotFound {
455 command_id: command_id.to_string(),
456 })
457 })?;
458
459 let final_state = match metadata.delivery_mode {
460 CommandDeliveryMode::Push => {
461 self.dispatch_command_push(command_id, &status.deployment_id)
462 .await?
463 }
464 CommandDeliveryMode::Pull => {
465 self.create_pending_index(
466 &status.deployment_id,
467 &metadata.target.resource_id,
468 command_id,
469 )
470 .await?;
471 debug!(
472 "Command {} ready for pull after upload (target will poll)",
473 command_id
474 );
475 CommandState::Pending
476 }
477 };
478
479 Ok(UploadCompleteResponse {
480 command_id: command_id.to_string(),
481 state: final_state,
482 })
483 }
484
485 pub async fn get_command_status(&self, command_id: &str) -> Result<CommandStatusResponse> {
489 let status = self
491 .command_registry
492 .get_command_status(command_id)
493 .await?
494 .ok_or_else(|| {
495 AlienError::new(ErrorData::CommandNotFound {
496 command_id: command_id.to_string(),
497 })
498 })?;
499
500 if let Some(deadline) = status.deadline {
502 if Utc::now() > deadline && !status.state.is_terminal() {
503 let won = self
508 .command_registry
509 .complete_command(command_id, CommandState::Expired, Utc::now(), None, None)
510 .await?;
511 if won {
512 self.delete_pending_index(
514 &status.deployment_id,
515 &status.target.resource_id,
516 command_id,
517 )
518 .await?;
519
520 return Ok(CommandStatusResponse {
522 command_id: command_id.to_string(),
523 state: CommandState::Expired,
524 attempt: status.attempt,
525 target: status.target,
526 response: None,
527 });
528 }
529 let status = self
532 .command_registry
533 .get_command_status(command_id)
534 .await?
535 .ok_or_else(|| {
536 AlienError::new(ErrorData::CommandNotFound {
537 command_id: command_id.to_string(),
538 })
539 })?;
540 let response = if status.state.is_terminal() {
541 self.get_response(command_id).await?
542 } else {
543 None
544 };
545 return Ok(CommandStatusResponse {
546 command_id: command_id.to_string(),
547 state: status.state,
548 attempt: status.attempt,
549 target: status.target,
550 response,
551 });
552 }
553 }
554
555 let response = if status.state.is_terminal() {
557 self.get_response(command_id).await?
558 } else {
559 None
560 };
561
562 Ok(CommandStatusResponse {
563 command_id: command_id.to_string(),
564 state: status.state,
565 attempt: status.attempt,
566 target: status.target,
567 response,
568 })
569 }
570
571 pub async fn submit_command_response(
575 &self,
576 command_id: &str,
577 mut response: CommandResponse,
578 ) -> Result<()> {
579 let status = self
581 .command_registry
582 .get_command_status(command_id)
583 .await?
584 .ok_or_else(|| {
585 AlienError::new(ErrorData::CommandNotFound {
586 command_id: command_id.to_string(),
587 })
588 })?;
589
590 if status.state.is_terminal() {
592 debug!(
593 "Ignoring duplicate response for terminal command {}",
594 command_id
595 );
596 return Ok(());
597 }
598
599 if status.state != CommandState::Dispatched {
601 return Err(AlienError::new(ErrorData::InvalidStateTransition {
602 from: status.state.as_ref().to_string(),
603 to: CommandState::Succeeded.as_ref().to_string(),
604 }));
605 }
606
607 if let CommandResponse::Success {
609 response: ref mut body,
610 } = response
611 {
612 if let BodySpec::Storage {
613 size,
614 storage_get_request,
615 storage_put_used,
616 } = body
617 {
618 if storage_get_request.is_none() && storage_put_used.unwrap_or(false) {
619 let get_request = self
620 .generate_response_storage_get_request(command_id)
621 .await?;
622 *body = BodySpec::Storage {
623 size: *size,
624 storage_get_request: Some(get_request),
625 storage_put_used: *storage_put_used,
626 };
627 }
628 }
629 }
630
631 self.store_response(command_id, &response).await?;
633
634 let (new_state, error) = if response.is_success() {
643 (CommandState::Succeeded, None)
644 } else if let CommandResponse::Error { code, message, .. } = &response {
645 (
646 CommandState::Failed,
647 Some(serde_json::json!({ "code": code, "message": message })),
648 )
649 } else {
650 (CommandState::Failed, None)
651 };
652
653 let response_size = match &response {
654 CommandResponse::Success {
655 response: BodySpec::Inline { inline_base64 },
656 } => Some(inline_base64.len() as u64),
657 CommandResponse::Success {
658 response: BodySpec::Storage { size, .. },
659 } => *size,
660 _ => None,
661 };
662
663 let won = self
673 .command_registry
674 .complete_command(command_id, new_state, Utc::now(), response_size, error)
675 .await?;
676 if !won {
677 debug!(
678 "Ignoring duplicate response for command {} (lost the terminal transition race)",
679 command_id
680 );
681 return Ok(());
682 }
683 self.store_response(command_id, &response).await?;
684
685 if let Err(e) = self.delete_lease(command_id).await {
690 warn!(
691 command_id,
692 error = %e,
693 "Failed to clean up lease after terminal response; will be reaped on next lease scan"
694 );
695 }
696
697 if let Err(e) = self
700 .delete_pending_index(
701 &status.deployment_id,
702 &status.target.resource_id,
703 command_id,
704 )
705 .await
706 {
707 warn!(
708 command_id,
709 error = %e,
710 "Failed to clean up pending index after terminal response; will be reaped on next lease scan"
711 );
712 }
713
714 info!(
715 "Command {} completed with state {:?}",
716 command_id, new_state
717 );
718 Ok(())
719 }
720
721 pub async fn acquire_lease(
725 &self,
726 deployment_id: &str,
727 lease_request: &LeaseRequest,
728 ) -> Result<LeaseResponse> {
729 let mut leases = Vec::new();
730
731 let target_prefix = format!(
734 "target:{}:{}:pending:",
735 deployment_id, lease_request.target.resource_id
736 );
737 let scan_result = self
738 .kv
739 .scan_prefix(&target_prefix, Some(lease_request.max_leases * 2), None)
740 .await
741 .into_alien_error()
742 .context(ErrorData::KvOperationFailed {
743 operation: "scan_prefix".to_string(),
744 key: target_prefix.clone(),
745 message: "Failed to scan for pending commands".to_string(),
746 })?;
747
748 for entry in scan_result.items {
749 let index_key = entry.key;
750 if leases.len() >= lease_request.max_leases {
751 break;
752 }
753
754 let command_id = self.extract_command_id_from_index_key(&index_key)?;
755
756 let lease_id = format!("lease_{}", Uuid::new_v4());
758 let lease_duration = Duration::from_secs(lease_request.lease_seconds);
759 let expires_at =
760 Utc::now() + chrono::Duration::seconds(lease_request.lease_seconds as i64);
761
762 let lease_data = LeaseData {
763 lease_id: lease_id.clone(),
764 acquired_at: Utc::now(),
765 expires_at,
766 owner: deployment_id.to_string(),
767 };
768
769 let lease_key = format!("cmd:{}:lease", command_id);
770 let lease_value = serde_json::to_vec(&lease_data).into_alien_error().context(
771 ErrorData::SerializationFailed {
772 message: "Failed to serialize lease data".to_string(),
773 data_type: Some("LeaseData".to_string()),
774 },
775 )?;
776
777 let options = Some(PutOptions {
778 ttl: Some(lease_duration),
779 condition: PutCondition::Absent,
780 });
781
782 let success = self
783 .kv
784 .put(&lease_key, lease_value, options)
785 .await
786 .context(ErrorData::KvOperationFailed {
787 operation: "put".to_string(),
788 key: lease_key.clone(),
789 message: "Failed to create lease".to_string(),
790 })?;
791
792 if !success {
793 continue;
795 }
796
797 let reverse_key = format!("lease:{}", lease_id);
802 self.kv
803 .put(
804 &reverse_key,
805 command_id.as_bytes().to_vec(),
806 Some(PutOptions {
807 ttl: Some(lease_duration),
808 condition: PutCondition::None,
809 }),
810 )
811 .await
812 .context(ErrorData::KvOperationFailed {
813 operation: "put".to_string(),
814 key: reverse_key,
815 message: "Failed to create lease reverse index".to_string(),
816 })?;
817
818 let mut metadata = match self
820 .command_registry
821 .get_command_metadata(&command_id)
822 .await?
823 {
824 Some(m) => m,
825 None => {
826 self.delete_lease(&command_id).await?;
828 let _ = self.kv.delete(&index_key, None).await;
829 continue;
830 }
831 };
832
833 if metadata.state == CommandState::Dispatched {
841 self.command_registry.increment_attempt(&command_id).await?;
842 metadata.attempt += 1;
843 }
844
845 if metadata.target != lease_request.target {
853 self.delete_lease(&command_id).await?;
854 return Err(AlienError::new(ErrorData::Other {
855 message: format!(
856 "Pending index corruption: command '{}' is indexed under target '{}' \
857 but the registry says it belongs to target '{}' — refusing to deliver",
858 command_id, lease_request.target.resource_id, metadata.target.resource_id,
859 ),
860 }));
861 }
862
863 if metadata.state.is_terminal() {
865 self.delete_lease(&command_id).await?;
867 let _ = self.kv.delete(&index_key, None).await;
868 continue;
869 }
870
871 if let Some(deadline) = metadata.deadline {
874 if Utc::now() > deadline {
875 let _ = self
876 .command_registry
877 .complete_command(
878 &command_id,
879 CommandState::Expired,
880 Utc::now(),
881 None,
882 None,
883 )
884 .await?;
885 self.delete_lease(&command_id).await?;
886 let _ = self.kv.delete(&index_key, None).await;
887 continue;
888 }
889 }
890
891 let params = match self.get_params(&command_id).await? {
893 Some(p) => p,
894 None => {
895 self.delete_lease(&command_id).await?;
897 continue;
898 }
899 };
900
901 let dispatched = self
906 .command_registry
907 .mark_dispatched_if_not_terminal(&command_id, Utc::now())
908 .await?;
909 if !dispatched {
910 debug!(
911 command_id = %command_id,
912 "Command turned terminal while leasing; releasing the lease"
913 );
914 self.delete_lease(&command_id).await?;
915 let _ = self.kv.delete(&index_key, None).await;
916 continue;
917 }
918
919 let mut envelope = self.build_envelope(&command_id, &metadata, params).await?;
928 Self::relativize_manager_urls(&mut envelope, &self.base_url);
929
930 leases.push(LeaseInfo {
931 lease_id,
932 lease_expires_at: expires_at,
933 command_id: command_id.clone(),
934 attempt: metadata.attempt,
935 envelope,
936 });
937 }
938
939 Ok(LeaseResponse { leases })
940 }
941
942 fn relativize_manager_urls(envelope: &mut Envelope, base_url: &str) {
947 let Ok(mut lease_endpoint) = reqwest::Url::parse(base_url) else {
948 return;
951 };
952 let Ok(mut segments) = lease_endpoint.path_segments_mut() else {
953 return;
954 };
955 segments.pop_if_empty().push("commands").push("leases");
956 drop(segments);
957 lease_endpoint.set_query(None);
958 lease_endpoint.set_fragment(None);
959
960 let relativize = |target: &mut String| {
961 let Ok(mut target_url) = reqwest::Url::parse(target.as_str()) else {
962 return;
963 };
964 let suffix = target
965 .find(['?', '#'])
966 .map(|index| target[index..].to_string())
967 .unwrap_or_default();
968 target_url.set_query(None);
969 target_url.set_fragment(None);
970 if let Some(relative) = lease_endpoint.make_relative(&target_url) {
971 *target = format!("{relative}{suffix}");
972 }
973 };
974
975 relativize(&mut envelope.response_handling.submit_response_url);
976 if let alien_core::presigned::PresignedRequestBackend::Http { url, .. } =
977 &mut envelope.response_handling.storage_upload_request.backend
978 {
979 relativize(url);
980 }
981 if let BodySpec::Storage {
982 storage_get_request: Some(request),
983 ..
984 } = &mut envelope.params
985 {
986 if let alien_core::presigned::PresignedRequestBackend::Http { url, .. } =
987 &mut request.backend
988 {
989 relativize(url);
990 }
991 }
992 }
993
994 pub async fn release_lease(&self, command_id: &str, lease_id: &str) -> Result<()> {
998 let lease_key = format!("cmd:{}:lease", command_id);
999
1000 if let Ok(Some(lease_data)) = self.kv.get(&lease_key).await {
1002 let lease: LeaseData = serde_json::from_slice(&lease_data.value)
1003 .into_alien_error()
1004 .context(ErrorData::SerializationFailed {
1005 message: "Failed to deserialize lease data".to_string(),
1006 data_type: Some("LeaseData".to_string()),
1007 })?;
1008
1009 if lease.lease_id != lease_id {
1010 return Err(AlienError::new(ErrorData::LeaseNotFound {
1011 lease_id: lease_id.to_string(),
1012 }));
1013 }
1014
1015 self.delete_lease(command_id).await?;
1017 let _ = self.kv.delete(&format!("lease:{}", lease_id), None).await;
1018
1019 let released = self
1022 .command_registry
1023 .update_command_state(command_id, CommandState::Pending, None, None, None, None)
1024 .await?;
1025 if released {
1026 self.command_registry.increment_attempt(command_id).await?;
1029 }
1030
1031 debug!(
1033 released,
1034 "Lease {} released for command {}", lease_id, command_id
1035 );
1036 }
1037
1038 Ok(())
1039 }
1040
1041 pub async fn get_command_deployment_id(&self, command_id: &str) -> Result<Option<String>> {
1046 let status = self.command_registry.get_command_status(command_id).await?;
1047 Ok(status.map(|s| s.deployment_id))
1048 }
1049
1050 pub async fn get_command_status_record(
1052 &self,
1053 command_id: &str,
1054 ) -> Result<Option<CommandStatus>> {
1055 self.command_registry.get_command_status(command_id).await
1056 }
1057
1058 pub async fn get_command_access_context(
1060 &self,
1061 command_id: &str,
1062 ) -> Result<Option<CommandAccessContext>> {
1063 self.command_registry
1064 .get_command_access_context(command_id)
1065 .await
1066 }
1067
1068 pub async fn get_lease_owner(&self, lease_id: &str) -> Result<Option<(String, String)>> {
1076 let reverse_key = format!("lease:{}", lease_id);
1077 let Some(command_id_bytes) =
1078 self.kv
1079 .get(&reverse_key)
1080 .await
1081 .context(ErrorData::KvOperationFailed {
1082 operation: "get".to_string(),
1083 key: reverse_key.clone(),
1084 message: "Failed to look up lease reverse index".to_string(),
1085 })?
1086 else {
1087 return Ok(None);
1088 };
1089 let command_id = String::from_utf8(command_id_bytes.value).map_err(|_| {
1090 AlienError::new(ErrorData::Other {
1091 message: format!("Lease reverse index '{}' is not valid UTF-8", reverse_key),
1092 })
1093 })?;
1094
1095 let lease_key = format!("cmd:{}:lease", command_id);
1096 let Some(lease_data) =
1097 self.kv
1098 .get(&lease_key)
1099 .await
1100 .context(ErrorData::KvOperationFailed {
1101 operation: "get".to_string(),
1102 key: lease_key,
1103 message: "Failed to look up lease".to_string(),
1104 })?
1105 else {
1106 return Ok(None);
1107 };
1108 let lease: LeaseData = serde_json::from_slice(&lease_data.value)
1109 .into_alien_error()
1110 .context(ErrorData::SerializationFailed {
1111 message: "Failed to deserialize lease data".to_string(),
1112 data_type: Some("LeaseData".to_string()),
1113 })?;
1114 if lease.lease_id != lease_id {
1115 return Ok(None);
1116 }
1117
1118 Ok(Some((command_id, lease.owner)))
1119 }
1120
1121 pub async fn release_lease_by_id(&self, lease_id: &str) -> Result<()> {
1123 match self.get_lease_owner(lease_id).await? {
1124 Some((command_id, _owner)) => self.release_lease(&command_id, lease_id).await,
1125 None => Err(AlienError::new(ErrorData::LeaseNotFound {
1126 lease_id: lease_id.to_string(),
1127 })),
1128 }
1129 }
1130
1131 async fn validate_create_command(&self, request: &CreateCommandRequest) -> Result<()> {
1136 validate_operation_result_contract_request(
1137 &request.command,
1138 request.operation_result_contract.is_some(),
1139 self.command_registry.persists_operation_result_contract(),
1140 )?;
1141
1142 if request.command.is_empty() {
1143 return Err(AlienError::new(ErrorData::InvalidCommand {
1144 message: "Command name cannot be empty".to_string(),
1145 }));
1146 }
1147
1148 validate_command_name(&request.command)?;
1156
1157 if request.deployment_id.is_empty() {
1158 return Err(AlienError::new(ErrorData::InvalidCommand {
1159 message: "Deployment ID cannot be empty".to_string(),
1160 }));
1161 }
1162
1163 if let Some(deadline) = request.deadline {
1164 if deadline <= Utc::now() {
1165 return Err(AlienError::new(ErrorData::InvalidCommand {
1166 message: "Deadline must be in the future".to_string(),
1167 }));
1168 }
1169 }
1170
1171 Ok(())
1172 }
1173
1174 fn compose_idempotency_key(
1182 deployment_id: &str,
1183 target_resource_id: &str,
1184 command_name: &str,
1185 idem_key: &str,
1186 ) -> String {
1187 debug_assert!(
1197 !target_resource_id.contains(':'),
1198 "target_resource_id must be ':'-free before key composition: {target_resource_id}"
1199 );
1200 format!(
1201 "{}:{}:{}:{}",
1202 deployment_id, target_resource_id, command_name, idem_key
1203 )
1204 }
1205
1206 fn storage_idempotency_key(composed_key: &str) -> String {
1210 let legacy_key = format!("idem:{composed_key}");
1211 if validate_key(&legacy_key).is_ok() {
1212 legacy_key
1213 } else {
1214 format!(
1215 "idem2:{}",
1216 hex::encode(Sha256::digest(composed_key.as_bytes()))
1217 )
1218 }
1219 }
1220
1221 async fn check_idempotency(&self, idem_key: &str) -> Result<Option<String>> {
1222 let key = Self::storage_idempotency_key(idem_key);
1223 if let Some(data) = self
1224 .kv
1225 .get(&key)
1226 .await
1227 .context(ErrorData::KvOperationFailed {
1228 operation: "get".to_string(),
1229 key: key.clone(),
1230 message: "Failed to check idempotency".to_string(),
1231 })?
1232 {
1233 let command_id = String::from_utf8(data.value).into_alien_error().context(
1234 ErrorData::SerializationFailed {
1235 message: "Invalid idempotency data".to_string(),
1236 data_type: Some("String".to_string()),
1237 },
1238 )?;
1239 return Ok(Some(command_id));
1240 }
1241 Ok(None)
1242 }
1243
1244 async fn store_idempotency(&self, idem_key: &str, command_id: &str) -> Result<Option<String>> {
1252 let key = Self::storage_idempotency_key(idem_key);
1253 let ttl = Duration::from_secs(24 * 60 * 60); let won = self
1255 .kv
1256 .put(
1257 &key,
1258 command_id.as_bytes().to_vec(),
1259 Some(PutOptions {
1260 ttl: Some(ttl),
1261 condition: PutCondition::Absent,
1262 }),
1263 )
1264 .await
1265 .context(ErrorData::KvOperationFailed {
1266 operation: "put".to_string(),
1267 key: key.clone(),
1268 message: "Failed to store idempotency".to_string(),
1269 })?;
1270 if won {
1271 return Ok(None);
1272 }
1273 match self.check_idempotency(idem_key).await? {
1277 Some(winner_id) => Ok(Some(winner_id)),
1278 None => Err(AlienError::new(ErrorData::Other {
1279 message: format!(
1280 "Idempotency key '{}' was concurrently claimed but has no winner entry",
1281 key
1282 ),
1283 })),
1284 }
1285 }
1286
1287 pub async fn store_params(&self, command_id: &str, params: &BodySpec) -> Result<()> {
1290 let key = format!("cmd:{}:params", command_id);
1291
1292 let data = CommandParamsData {
1294 params: params.clone(),
1295 };
1296 let value = serde_json::to_vec(&data).into_alien_error().context(
1297 ErrorData::SerializationFailed {
1298 message: "Failed to serialize params".to_string(),
1299 data_type: Some("CommandParamsData".to_string()),
1300 },
1301 )?;
1302
1303 if value.len() <= KV_VALUE_THRESHOLD {
1305 self.kv
1306 .put(&key, value, None)
1307 .await
1308 .context(ErrorData::KvOperationFailed {
1309 operation: "put".to_string(),
1310 key: key.clone(),
1311 message: "Failed to store params".to_string(),
1312 })?;
1313 return Ok(());
1314 }
1315
1316 if let BodySpec::Inline { inline_base64 } = params {
1318 let raw_bytes = general_purpose::STANDARD
1319 .decode(inline_base64)
1320 .into_alien_error()
1321 .context(ErrorData::SerializationFailed {
1322 message: "Failed to decode inline base64 params for auto-promotion".to_string(),
1323 data_type: Some("base64".to_string()),
1324 })?;
1325
1326 let raw_len = raw_bytes.len() as u64;
1327 let blob_path = StoragePath::from(format!("arc/commands/{}/params", command_id));
1328
1329 self.storage
1330 .put(&blob_path, Bytes::from(raw_bytes).into())
1331 .await
1332 .into_alien_error()
1333 .context(ErrorData::StorageOperationFailed {
1334 message: "Failed to auto-promote params to blob storage".to_string(),
1335 operation: Some("put".to_string()),
1336 path: Some(blob_path.to_string()),
1337 })?;
1338
1339 debug!(
1340 "Auto-promoted params for command {} to blob ({} bytes raw)",
1341 command_id, raw_len
1342 );
1343
1344 let promoted = CommandParamsData {
1346 params: BodySpec::Storage {
1347 size: Some(raw_len),
1348 storage_get_request: None,
1349 storage_put_used: Some(true),
1350 },
1351 };
1352 let promoted_value = serde_json::to_vec(&promoted).into_alien_error().context(
1353 ErrorData::SerializationFailed {
1354 message: "Failed to serialize promoted params reference".to_string(),
1355 data_type: Some("CommandParamsData".to_string()),
1356 },
1357 )?;
1358 self.kv.put(&key, promoted_value, None).await.context(
1359 ErrorData::KvOperationFailed {
1360 operation: "put".to_string(),
1361 key: key.clone(),
1362 message: "Failed to store promoted params reference".to_string(),
1363 },
1364 )?;
1365 return Ok(());
1366 }
1367
1368 self.kv
1370 .put(&key, value, None)
1371 .await
1372 .context(ErrorData::KvOperationFailed {
1373 operation: "put".to_string(),
1374 key: key.clone(),
1375 message: "Failed to store params".to_string(),
1376 })?;
1377 Ok(())
1378 }
1379
1380 pub async fn get_params(&self, command_id: &str) -> Result<Option<BodySpec>> {
1381 let key = format!("cmd:{}:params", command_id);
1382 if let Some(value) = self
1383 .kv
1384 .get(&key)
1385 .await
1386 .context(ErrorData::KvOperationFailed {
1387 operation: "get".to_string(),
1388 key: key.clone(),
1389 message: "Failed to get params".to_string(),
1390 })?
1391 {
1392 let data: CommandParamsData = serde_json::from_slice(&value.value)
1393 .into_alien_error()
1394 .context(ErrorData::SerializationFailed {
1395 message: "Failed to deserialize params".to_string(),
1396 data_type: Some("CommandParamsData".to_string()),
1397 })?;
1398 return Ok(Some(data.params));
1399 }
1400 Ok(None)
1401 }
1402
1403 pub async fn store_response(&self, command_id: &str, response: &CommandResponse) -> Result<()> {
1406 let key = format!("cmd:{}:response", command_id);
1407 let data = CommandResponseData {
1408 response: response.clone(),
1409 };
1410 let value = serde_json::to_vec(&data).into_alien_error().context(
1411 ErrorData::SerializationFailed {
1412 message: "Failed to serialize response".to_string(),
1413 data_type: Some("CommandResponseData".to_string()),
1414 },
1415 )?;
1416
1417 if value.len() <= KV_VALUE_THRESHOLD {
1419 self.kv
1420 .put(&key, value, None)
1421 .await
1422 .context(ErrorData::KvOperationFailed {
1423 operation: "put".to_string(),
1424 key: key.clone(),
1425 message: "Failed to store response".to_string(),
1426 })?;
1427 return Ok(());
1428 }
1429
1430 if let CommandResponse::Success {
1432 response: BodySpec::Inline { inline_base64 },
1433 } = response
1434 {
1435 let raw_bytes = general_purpose::STANDARD
1436 .decode(inline_base64)
1437 .into_alien_error()
1438 .context(ErrorData::SerializationFailed {
1439 message: "Failed to decode inline base64 response for auto-promotion"
1440 .to_string(),
1441 data_type: Some("base64".to_string()),
1442 })?;
1443
1444 let raw_len = raw_bytes.len() as u64;
1445 let blob_path = StoragePath::from(format!("arc/commands/{}/response", command_id));
1446
1447 self.storage
1448 .put(&blob_path, Bytes::from(raw_bytes).into())
1449 .await
1450 .into_alien_error()
1451 .context(ErrorData::StorageOperationFailed {
1452 message: "Failed to auto-promote response to blob storage".to_string(),
1453 operation: Some("put".to_string()),
1454 path: Some(blob_path.to_string()),
1455 })?;
1456
1457 let get_request = self
1459 .generate_response_storage_get_request(command_id)
1460 .await?;
1461
1462 debug!(
1463 "Auto-promoted response for command {} to blob ({} bytes raw)",
1464 command_id, raw_len
1465 );
1466
1467 let promoted = CommandResponseData {
1469 response: CommandResponse::Success {
1470 response: BodySpec::Storage {
1471 size: Some(raw_len),
1472 storage_get_request: Some(get_request),
1473 storage_put_used: Some(true),
1474 },
1475 },
1476 };
1477 let promoted_value = serde_json::to_vec(&promoted).into_alien_error().context(
1478 ErrorData::SerializationFailed {
1479 message: "Failed to serialize promoted response reference".to_string(),
1480 data_type: Some("CommandResponseData".to_string()),
1481 },
1482 )?;
1483 self.kv.put(&key, promoted_value, None).await.context(
1484 ErrorData::KvOperationFailed {
1485 operation: "put".to_string(),
1486 key: key.clone(),
1487 message: "Failed to store promoted response reference".to_string(),
1488 },
1489 )?;
1490 return Ok(());
1491 }
1492
1493 self.kv
1495 .put(&key, value, None)
1496 .await
1497 .context(ErrorData::KvOperationFailed {
1498 operation: "put".to_string(),
1499 key: key.clone(),
1500 message: "Failed to store response".to_string(),
1501 })?;
1502 Ok(())
1503 }
1504
1505 pub async fn get_response(&self, command_id: &str) -> Result<Option<CommandResponse>> {
1506 let key = format!("cmd:{}:response", command_id);
1507 if let Some(value) = self
1508 .kv
1509 .get(&key)
1510 .await
1511 .context(ErrorData::KvOperationFailed {
1512 operation: "get".to_string(),
1513 key: key.clone(),
1514 message: "Failed to get response".to_string(),
1515 })?
1516 {
1517 let data: CommandResponseData = serde_json::from_slice(&value.value)
1518 .into_alien_error()
1519 .context(ErrorData::SerializationFailed {
1520 message: "Failed to deserialize response".to_string(),
1521 data_type: Some("CommandResponseData".to_string()),
1522 })?;
1523 return Ok(Some(data.response));
1524 }
1525 Ok(None)
1526 }
1527
1528 async fn create_pending_index(
1531 &self,
1532 deployment_id: &str,
1533 target_resource_id: &str,
1534 command_id: &str,
1535 ) -> Result<()> {
1536 debug_assert!(
1540 !target_resource_id.contains(':'),
1541 "target_resource_id must be ':'-free in the pending index: {target_resource_id}"
1542 );
1543 let timestamp = Utc::now().timestamp_nanos_opt().unwrap_or(0);
1544 let key = format!(
1545 "target:{}:{}:pending:{}:{}",
1546 deployment_id, target_resource_id, timestamp, command_id
1547 );
1548
1549 self.kv
1551 .put(&key, vec![], None)
1552 .await
1553 .context(ErrorData::KvOperationFailed {
1554 operation: "put".to_string(),
1555 key: key.clone(),
1556 message: "Failed to create pending index".to_string(),
1557 })?;
1558 Ok(())
1559 }
1560
1561 async fn delete_pending_index(
1562 &self,
1563 deployment_id: &str,
1564 target_resource_id: &str,
1565 command_id: &str,
1566 ) -> Result<()> {
1567 let prefix = format!("target:{}:{}:pending:", deployment_id, target_resource_id);
1569 let scan_result = self
1570 .kv
1571 .scan_prefix(&prefix, Some(100), None)
1572 .await
1573 .into_alien_error()
1574 .context(ErrorData::KvOperationFailed {
1575 operation: "scan_prefix".to_string(),
1576 key: prefix.clone(),
1577 message: "Failed to scan pending index".to_string(),
1578 })?;
1579
1580 for entry in scan_result.items {
1581 if entry.key.ends_with(&format!(":{}", command_id)) {
1582 let _ = self.kv.delete(&entry.key, None).await;
1583 break;
1584 }
1585 }
1586 Ok(())
1587 }
1588
1589 async fn delete_lease(&self, command_id: &str) -> Result<()> {
1592 let key = format!("cmd:{}:lease", command_id);
1593 let _ = self.kv.delete(&key, None).await;
1594 Ok(())
1595 }
1596
1597 pub async fn reap_expired_commands(&self) -> Result<u32> {
1609 let now = Utc::now();
1610 let mut expired = 0u32;
1611 let mut cursor: Option<String> = None;
1612 for _ in 0..64 {
1617 let scan = self
1618 .kv
1619 .scan_prefix("deadline:", Some(256), cursor.clone())
1620 .await
1621 .into_alien_error()
1622 .context(ErrorData::KvOperationFailed {
1623 operation: "scan_prefix".to_string(),
1624 key: "deadline:".to_string(),
1625 message: "Failed to scan the deadline index".to_string(),
1626 })?;
1627 let next_cursor = scan.next_cursor.clone();
1628 for entry in scan.items {
1629 let Ok(data) = serde_json::from_slice::<DeadlineIndexData>(&entry.value) else {
1630 warn!(key = %entry.key, "Unparseable deadline index entry; deleting");
1631 let _ = self.kv.delete(&entry.key, None).await;
1632 continue;
1633 };
1634 if data.deadline > now {
1635 continue;
1638 }
1639
1640 let status = self
1641 .command_registry
1642 .get_command_status(&data.command_id)
1643 .await?;
1644 match status {
1645 None => {
1646 let _ = self.kv.delete(&entry.key, None).await;
1647 }
1648 Some(status) if status.state.is_terminal() => {
1649 let _ = self.kv.delete(&entry.key, None).await;
1650 }
1651 Some(status) => {
1652 let won = self
1653 .command_registry
1654 .complete_command(
1655 &data.command_id,
1656 CommandState::Expired,
1657 now,
1658 None,
1659 Some(serde_json::json!({
1660 "code": "COMMAND_EXPIRED",
1661 "message": format!("Deadline {} elapsed", data.deadline.to_rfc3339()),
1662 })),
1663 )
1664 .await?;
1665 if won {
1666 expired += 1;
1667 info!(command_id = %data.command_id, "Expired overdue command");
1668 let _ = self.delete_lease(&data.command_id).await;
1669 let _ = self
1670 .delete_pending_index(
1671 &status.deployment_id,
1672 &status.target.resource_id,
1673 &data.command_id,
1674 )
1675 .await;
1676 }
1677 let _ = self.kv.delete(&entry.key, None).await;
1678 }
1679 }
1680 }
1681 match next_cursor {
1682 Some(next) => cursor = Some(next),
1683 None => break,
1684 }
1685 }
1686 Ok(expired)
1687 }
1688
1689 async fn create_deadline_index(&self, command_id: &str, deadline: DateTime<Utc>) -> Result<()> {
1692 let key = format!(
1693 "deadline:{}:{}",
1694 deadline.timestamp_nanos_opt().unwrap_or(0),
1695 command_id
1696 );
1697
1698 let data = DeadlineIndexData {
1699 command_id: command_id.to_string(),
1700 deadline,
1701 };
1702 let value = serde_json::to_vec(&data).into_alien_error().context(
1703 ErrorData::SerializationFailed {
1704 message: "Failed to serialize deadline index".to_string(),
1705 data_type: Some("DeadlineIndexData".to_string()),
1706 },
1707 )?;
1708
1709 const DEADLINE_INDEX_GRACE: chrono::Duration = chrono::Duration::days(7);
1716 let ttl = deadline
1717 .signed_duration_since(Utc::now())
1718 .checked_add(&DEADLINE_INDEX_GRACE)
1719 .unwrap_or(DEADLINE_INDEX_GRACE);
1720 let options = (ttl.num_seconds() > 0).then(|| PutOptions {
1721 ttl: Some(Duration::from_secs(ttl.num_seconds() as u64)),
1722 condition: PutCondition::None,
1723 });
1724
1725 self.kv
1726 .put(&key, value, options)
1727 .await
1728 .context(ErrorData::KvOperationFailed {
1729 operation: "put".to_string(),
1730 key: key.clone(),
1731 message: "Failed to create deadline index".to_string(),
1732 })?;
1733 Ok(())
1734 }
1735
1736 async fn dispatch_command_push(
1739 &self,
1740 command_id: &str,
1741 deployment_id: &str,
1742 ) -> Result<CommandState> {
1743 let metadata = self
1745 .command_registry
1746 .get_command_metadata(command_id)
1747 .await?
1748 .ok_or_else(|| {
1749 AlienError::new(ErrorData::CommandNotFound {
1750 command_id: command_id.to_string(),
1751 })
1752 })?;
1753
1754 let params = self.get_params(command_id).await?.ok_or_else(|| {
1756 AlienError::new(ErrorData::CommandNotFound {
1757 command_id: command_id.to_string(),
1758 })
1759 })?;
1760
1761 let envelope = self.build_envelope(command_id, &metadata, params).await?;
1763
1764 if !self
1770 .command_registry
1771 .mark_dispatched_if_not_terminal(command_id, Utc::now())
1772 .await?
1773 {
1774 return Ok(self
1775 .command_registry
1776 .get_command_status(command_id)
1777 .await?
1778 .map(|status| status.state)
1779 .unwrap_or(CommandState::Dispatched));
1780 }
1781
1782 if let Err(error) = self.command_dispatcher.dispatch(&envelope).await {
1790 if is_definite_dispatch_rejection(&error) {
1791 let delivery_failure = CommandResponse::error(
1792 "DELIVERY_FAILED",
1793 "Worker runtime did not accept command delivery",
1794 );
1795 self.submit_command_response(command_id, delivery_failure)
1796 .await?;
1797 warn!(
1798 command_id,
1799 deployment_id,
1800 error = %error,
1801 "Push dispatch was definitely rejected; command marked Failed"
1802 );
1803 return Ok(CommandState::Failed);
1804 }
1805
1806 let error = error.context(ErrorData::TransportDispatchFailed {
1807 message: "Failed to dispatch command".to_string(),
1808 transport_type: None,
1809 target: Some(deployment_id.to_string()),
1810 });
1811 warn!(
1812 command_id,
1813 deployment_id,
1814 error = %error,
1815 "Push dispatch acknowledgement failed; command remains Dispatched for a possible late response"
1816 );
1817 return Ok(CommandState::Dispatched);
1818 }
1819
1820 info!("Command {} dispatched via push", envelope.command_id);
1821 Ok(CommandState::Dispatched)
1822 }
1823
1824 async fn build_envelope(
1825 &self,
1826 command_id: &str,
1827 metadata: &CommandEnvelopeData,
1828 mut params: BodySpec,
1829 ) -> Result<Envelope> {
1830 let response_handling = self.create_response_handling(command_id).await?;
1831
1832 if let BodySpec::Storage { size, .. } = ¶ms {
1835 let raw_size = size.unwrap_or(0) as usize;
1836 if raw_size > 0 && raw_size <= self.inline_max_bytes {
1837 let blob_path = StoragePath::from(format!("arc/commands/{}/params", command_id));
1838 match self.storage.get(&blob_path).await {
1839 Ok(get_result) => match get_result.bytes().await {
1840 Ok(raw_bytes) => {
1841 params = BodySpec::inline(&raw_bytes);
1842 debug!(
1843 "Re-inlined params for command {} ({} bytes) into envelope",
1844 command_id, raw_size
1845 );
1846 }
1847 Err(e) => {
1848 debug!(
1849 "Failed to read blob bytes for re-inline (command {}), falling back to presigned URL: {}",
1850 command_id, e
1851 );
1852 }
1853 },
1854 Err(e) => {
1855 debug!(
1856 "Failed to read blob for re-inline (command {}), falling back to presigned URL: {}",
1857 command_id, e
1858 );
1859 }
1860 }
1861 }
1862 }
1863
1864 if let BodySpec::Storage {
1869 size,
1870 storage_get_request: _,
1871 storage_put_used,
1872 } = ¶ms
1873 {
1874 let get_request = self.generate_storage_get_request(command_id).await?;
1875 params = BodySpec::Storage {
1876 size: *size,
1877 storage_get_request: Some(get_request),
1878 storage_put_used: *storage_put_used,
1879 };
1880 }
1881
1882 Ok(Envelope::new(
1883 metadata.deployment_id.clone(),
1884 metadata.target.clone(),
1885 command_id.to_string(),
1886 metadata.attempt,
1887 metadata.deadline,
1888 metadata.command.clone(),
1889 params,
1890 response_handling,
1891 ))
1892 }
1893
1894 async fn create_response_handling(&self, command_id: &str) -> Result<ResponseHandling> {
1895 let upload_path = StoragePath::from(format!("arc/commands/{}/response", command_id));
1896 let expires_in = Duration::from_secs(Self::RESPONSE_CREDENTIAL_LIFETIME_SECS);
1897 let presigned = self
1898 .storage
1899 .presigned_put(&upload_path, expires_in)
1900 .await
1901 .context(ErrorData::StorageOperationFailed {
1902 message: "Failed to create response upload URL".to_string(),
1903 operation: Some("presigned_put".to_string()),
1904 path: Some(upload_path.to_string()),
1905 })?;
1906
1907 let (response_token, expires) = self.sign_response_url(command_id);
1908
1909 Ok(ResponseHandling {
1910 max_inline_bytes: self.inline_max_bytes as u64,
1911 submit_response_url: format!(
1912 "{}/commands/{}/response?response_token={}&expires={}",
1913 self.base_url.trim_end_matches('/'),
1914 command_id,
1915 response_token,
1916 expires,
1917 ),
1918 storage_upload_request: presigned,
1919 })
1920 }
1921
1922 async fn generate_params_upload(&self, command_id: &str) -> Result<StorageUpload> {
1923 let upload_path = StoragePath::from(format!("arc/commands/{}/params", command_id));
1924 let expires_in = Duration::from_secs(3600);
1925 let presigned = self
1926 .storage
1927 .presigned_put(&upload_path, expires_in)
1928 .await
1929 .into_alien_error()
1930 .context(ErrorData::StorageOperationFailed {
1931 message: "Failed to create presigned URL".to_string(),
1932 operation: Some("presigned_put".to_string()),
1933 path: Some(upload_path.to_string()),
1934 })?;
1935
1936 Ok(StorageUpload {
1937 put_request: presigned.clone(),
1938 expires_at: presigned.expiration,
1939 })
1940 }
1941
1942 async fn generate_storage_get_request(&self, command_id: &str) -> Result<PresignedRequest> {
1943 let path = StoragePath::from(format!("arc/commands/{}/params", command_id));
1944 let expires_in = Duration::from_secs(3600);
1945 self.storage.presigned_get(&path, expires_in).await.context(
1946 ErrorData::StorageOperationFailed {
1947 message: "Failed to create storage get request".to_string(),
1948 operation: Some("presigned_get".to_string()),
1949 path: Some(path.to_string()),
1950 },
1951 )
1952 }
1953
1954 async fn generate_response_storage_get_request(
1955 &self,
1956 command_id: &str,
1957 ) -> Result<PresignedRequest> {
1958 let path = StoragePath::from(format!("arc/commands/{}/response", command_id));
1959 let expires_in = Duration::from_secs(3600);
1960 self.storage.presigned_get(&path, expires_in).await.context(
1961 ErrorData::StorageOperationFailed {
1962 message: "Failed to create response storage get request".to_string(),
1963 operation: Some("presigned_get".to_string()),
1964 path: Some(path.to_string()),
1965 },
1966 )
1967 }
1968
1969 fn extract_command_id_from_index_key(&self, index_key: &str) -> Result<String> {
1970 index_key
1971 .split(':')
1972 .last()
1973 .ok_or_else(|| {
1974 AlienError::new(ErrorData::Other {
1975 message: format!("Invalid index key format: {}", index_key),
1976 })
1977 })
1978 .map(|s| s.to_string())
1979 }
1980}
1981
1982fn validate_operation_result_contract_request(
1983 command: &str,
1984 contract_present: bool,
1985 registry_supports_contract: bool,
1986) -> Result<()> {
1987 let operation_command = command.strip_prefix("operation/v1/").is_some_and(|digest| {
1988 digest.len() == 64
1989 && digest
1990 .bytes()
1991 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
1992 });
1993 if operation_command && !contract_present {
1994 return Err(AlienError::new(ErrorData::InvalidCommand {
1995 message: "Version-qualified operation commands require an immutable result contract"
1996 .to_string(),
1997 }));
1998 }
1999 if contract_present && (!operation_command || !registry_supports_contract) {
2000 return Err(AlienError::new(ErrorData::InvalidCommand {
2001 message:
2002 "This command registry cannot persist the operation result contract before dispatch"
2003 .to_string(),
2004 }));
2005 }
2006 Ok(())
2007}
2008
2009#[cfg(test)]
2010mod relative_url_tests {
2011 use super::*;
2012 use alien_core::presigned::PresignedOperation;
2013 use std::collections::HashMap;
2014
2015 fn http_request(url: &str, operation: PresignedOperation) -> PresignedRequest {
2016 PresignedRequest::new_http(
2017 url.to_string(),
2018 match operation {
2019 PresignedOperation::Get => "GET",
2020 PresignedOperation::Put => "PUT",
2021 PresignedOperation::Delete => "DELETE",
2022 }
2023 .to_string(),
2024 HashMap::new(),
2025 operation,
2026 "commands/test".to_string(),
2027 Utc::now() + chrono::Duration::minutes(5),
2028 )
2029 }
2030
2031 #[test]
2032 fn leased_manager_urls_are_relative_to_lease_endpoint() {
2033 let mut envelope = Envelope::new(
2034 "deployment",
2035 CommandTarget::new("daemon", CommandTargetType::Daemon),
2036 "command",
2037 1,
2038 None,
2039 "run",
2040 BodySpec::Storage {
2041 size: Some(2048),
2042 storage_get_request: Some(http_request(
2043 "http://manager.internal/storage/params?signature=params",
2044 PresignedOperation::Get,
2045 )),
2046 storage_put_used: Some(true),
2047 },
2048 ResponseHandling {
2049 max_inline_bytes: 1024,
2050 submit_response_url:
2051 "http://manager.internal/v1/commands/command/response?response_token=DoNotCanonicalize%2FValue&expires=1"
2052 .to_string(),
2053 storage_upload_request: http_request(
2054 "http://manager.internal/v1/storage/response?signature=DoNotCanonicalize%2FUpload",
2055 PresignedOperation::Put,
2056 ),
2057 },
2058 );
2059
2060 CommandServer::relativize_manager_urls(&mut envelope, "http://manager.internal/v1");
2061
2062 assert_eq!(
2063 envelope.response_handling.submit_response_url,
2064 "command/response?response_token=DoNotCanonicalize%2FValue&expires=1"
2065 );
2066 assert_eq!(
2067 envelope.response_handling.storage_upload_request.url(),
2068 "../storage/response?signature=DoNotCanonicalize%2FUpload"
2069 );
2070 let BodySpec::Storage {
2071 storage_get_request: Some(params),
2072 ..
2073 } = &envelope.params
2074 else {
2075 panic!("storage params request");
2076 };
2077 assert_eq!(params.url(), "../../storage/params?signature=params");
2078
2079 envelope.response_handling.storage_upload_request = http_request(
2080 "https://storage.example.com/result?signature=cloud",
2081 PresignedOperation::Put,
2082 );
2083 CommandServer::relativize_manager_urls(&mut envelope, "http://manager.internal/v1");
2084 assert_eq!(
2085 envelope.response_handling.storage_upload_request.url(),
2086 "https://storage.example.com/result?signature=cloud",
2087 "cloud-presigned URLs must remain byte-for-byte absolute"
2088 );
2089 }
2090}
2091
2092#[cfg(test)]
2093mod idempotency_key_tests {
2094 use super::*;
2095 use crate::server::{validate_command_name, validate_command_target_id};
2096
2097 #[test]
2098 fn storage_key_preserves_portable_legacy_keys_and_encodes_versioned_commands() {
2099 let legacy = CommandServer::compose_idempotency_key("dep", "operator", "refresh", "retry");
2100 assert_eq!(
2101 CommandServer::storage_idempotency_key(&legacy),
2102 "idem:dep:operator:refresh:retry"
2103 );
2104
2105 let versioned =
2106 CommandServer::compose_idempotency_key("dep", "operator", "operation/v1/abc", "retry");
2107 let encoded = CommandServer::storage_idempotency_key(&versioned);
2108 assert!(encoded.starts_with("idem2:"));
2109 assert!(validate_key(&encoded).is_ok());
2110 assert_eq!(encoded, CommandServer::storage_idempotency_key(&versioned));
2111 assert_ne!(
2112 encoded,
2113 CommandServer::storage_idempotency_key(&CommandServer::compose_idempotency_key(
2114 "dep",
2115 "operator",
2116 "operation/v1/def",
2117 "retry",
2118 )),
2119 );
2120 }
2121
2122 #[test]
2123 fn definite_dispatch_rejection_is_classified_by_typed_error_data() {
2124 let rejected = AlienError::new(ErrorData::TransportDispatchRejected {
2125 message: "not accepted".to_string(),
2126 transport_type: Some("http".to_string()),
2127 target: Some("command-id".to_string()),
2128 });
2129 assert!(is_definite_dispatch_rejection(&rejected));
2130
2131 let ambiguous = AlienError::new(ErrorData::TransportDispatchFailed {
2132 message: "acknowledgement lost".to_string(),
2133 transport_type: Some("http".to_string()),
2134 target: Some("command-id".to_string()),
2135 });
2136 assert!(!is_definite_dispatch_rejection(&ambiguous));
2137 }
2138
2139 #[test]
2148 fn target_id_colon_guard_prevents_idempotency_key_collision() {
2149 let colliding = CommandServer::compose_idempotency_key("dep", "svc", "a:b", "k");
2150 assert_eq!(colliding, "dep:svc:a:b:k");
2151
2152 assert!(
2154 validate_command_target_id("svc:a").is_err(),
2155 "a ':'-bearing target id must be rejected so it cannot forge the rid segment"
2156 );
2157 assert!(validate_command_target_id("svc").is_ok());
2158 }
2159
2160 #[test]
2168 fn command_name_colon_guard_prevents_idempotency_key_collision() {
2169 let forged = CommandServer::compose_idempotency_key("dep", "svc", "a:b", "c");
2171 let legitimate = CommandServer::compose_idempotency_key("dep", "svc", "a", "b:c");
2172 assert_eq!(
2173 forged, legitimate,
2174 "these inputs are exactly the colliding pair the guard must separate"
2175 );
2176 assert_eq!(legitimate, "dep:svc:a:b:c");
2177
2178 let err = validate_command_name("a:b").expect_err("':'-bearing command must be rejected");
2183 assert_eq!(err.code, "INVALID_COMMAND");
2184 assert!(validate_command_name("a").is_ok());
2185 }
2186
2187 #[test]
2188 fn versioned_operation_requires_atomic_result_contract_support() {
2189 let command = format!("operation/v1/{}", "a".repeat(64));
2190
2191 assert!(validate_operation_result_contract_request(&command, true, true).is_ok());
2192 assert!(validate_operation_result_contract_request(&command, false, true).is_err());
2193 assert!(validate_operation_result_contract_request(&command, true, false).is_err());
2194 assert!(validate_operation_result_contract_request("postgres/health", true, true).is_err());
2195 }
2196}