1use std::sync::Arc;
8use std::time::Duration;
9
10use alien_bindings::presigned::PresignedRequest;
11use alien_bindings::traits::{Kv, PutCondition, PutOptions, Storage};
12use alien_error::{AlienError, Context, ContextError, IntoAlienError};
13use chrono::{DateTime, Utc};
14use hex;
15use hmac::{Hmac, Mac};
16use serde::{Deserialize, Serialize};
17use sha2::Sha256;
18use tracing::{debug, info, warn};
19use uuid::Uuid;
20
21use base64::{engine::general_purpose, Engine as _};
22use bytes::Bytes;
23use object_store::path::Path as StoragePath;
24
25use crate::error::{ErrorData, Result};
26use crate::types::*;
27use crate::INLINE_MAX_BYTES;
28
29const KV_VALUE_THRESHOLD: usize = 20_000;
32
33fn is_definite_dispatch_rejection(error: &crate::error::Error) -> bool {
34 matches!(
35 error.error.as_ref(),
36 Some(ErrorData::TransportDispatchRejected { .. })
37 )
38}
39
40pub mod axum_handlers;
41pub mod command_registry;
42pub mod storage;
43
44pub use crate::dispatchers::{CommandDispatcher, NullCommandDispatcher};
45pub use axum_handlers::{
46 create_axum_router, CommandPayloadResponse, HasCommandServer, StorePayloadRequest,
47};
48pub use command_registry::{
49 delivery_mode_for, select_command_target, validate_command_name, validate_command_target_id,
50 CommandAccessContext, CommandEnvelopeData, CommandMetadata, CommandRegistry, CommandStatus,
51 InMemoryCommandRegistry, ResolvedCommandTarget,
52};
53
54#[derive(Debug, Clone, Serialize, Deserialize)]
60struct CommandParamsData {
61 pub params: BodySpec,
62}
63
64#[derive(Debug, Clone, Serialize, Deserialize)]
66struct CommandResponseData {
67 pub response: CommandResponse,
68}
69
70#[derive(Debug, Clone, Serialize, Deserialize)]
72struct LeaseData {
73 pub lease_id: String,
74 pub acquired_at: DateTime<Utc>,
75 pub expires_at: DateTime<Utc>,
76 pub owner: String,
77}
78
79#[derive(Debug, Clone, Serialize, Deserialize)]
81struct DeadlineIndexData {
82 pub command_id: String,
83 pub deadline: DateTime<Utc>,
84}
85
86pub struct CommandServer {
95 kv: Arc<dyn Kv>,
96 storage: Arc<dyn Storage>,
97 command_dispatcher: Arc<dyn CommandDispatcher>,
98 command_registry: Arc<dyn CommandRegistry>,
99 inline_max_bytes: usize,
100 base_url: String,
101 response_signing_key: Vec<u8>,
102}
103
104impl CommandServer {
105 pub fn new(
107 kv: Arc<dyn Kv>,
108 storage: Arc<dyn Storage>,
109 command_dispatcher: Arc<dyn CommandDispatcher>,
110 command_registry: Arc<dyn CommandRegistry>,
111 base_url: String,
112 response_signing_key: Vec<u8>,
113 ) -> Self {
114 Self {
115 kv,
116 storage,
117 command_dispatcher,
118 command_registry,
119 inline_max_bytes: INLINE_MAX_BYTES,
120 base_url,
121 response_signing_key,
122 }
123 }
124
125 pub fn with_inline_limit(
127 kv: Arc<dyn Kv>,
128 storage: Arc<dyn Storage>,
129 command_dispatcher: Arc<dyn CommandDispatcher>,
130 command_registry: Arc<dyn CommandRegistry>,
131 base_url: String,
132 inline_max_bytes: usize,
133 response_signing_key: Vec<u8>,
134 ) -> Self {
135 Self {
136 kv,
137 storage,
138 command_dispatcher,
139 command_registry,
140 inline_max_bytes,
141 base_url,
142 response_signing_key,
143 }
144 }
145
146 const MAX_RESPONSE_TOKEN_LIFETIME_SECS: i64 = 7200;
148 const RESPONSE_CREDENTIAL_LIFETIME_SECS: u64 = 7200;
152
153 fn sign_response_url(&self, command_id: &str) -> (String, i64) {
158 let expires = Utc::now().timestamp() + Self::RESPONSE_CREDENTIAL_LIFETIME_SECS as i64;
159 let message = format!("commands.v1:{}:{}", command_id, expires);
160
161 type HmacSha256 = Hmac<Sha256>;
162 let mut mac =
163 HmacSha256::new_from_slice(&self.response_signing_key).expect("HMAC accepts any key");
164 mac.update(message.as_bytes());
165 let result = mac.finalize();
166 let token = hex::encode(result.into_bytes());
167
168 (token, expires)
169 }
170
171 pub fn verify_response_token(&self, command_id: &str, token: &str, expires: i64) -> bool {
176 if token.len() != 64 {
178 return false;
179 }
180
181 let message = format!("commands.v1:{}:{}", command_id, expires);
182
183 type HmacSha256 = Hmac<Sha256>;
184 let mut mac =
185 HmacSha256::new_from_slice(&self.response_signing_key).expect("HMAC accepts any key");
186 mac.update(message.as_bytes());
187
188 let Ok(token_bytes) = hex::decode(token) else {
190 return false;
191 };
192 let hmac_valid = mac.verify_slice(&token_bytes).is_ok();
193
194 let now = Utc::now().timestamp();
196 let not_expired = now <= expires;
197 let within_max_lifetime = expires <= now + Self::MAX_RESPONSE_TOKEN_LIFETIME_SECS;
198
199 hmac_valid && not_expired && within_max_lifetime
200 }
201
202 pub async fn create_command(
214 &self,
215 request: CreateCommandRequest,
216 ) -> Result<CreateCommandResponse> {
217 self.validate_create_command(&request).await?;
219
220 let resolved_target = self
223 .command_registry
224 .resolve_target(
225 &request.deployment_id,
226 request.target_resource_id.as_deref(),
227 )
228 .await?;
229
230 let composed_idempotency_key = request.idempotency_key.as_ref().map(|idem_key| {
237 Self::compose_idempotency_key(
238 &request.deployment_id,
239 &resolved_target.target.resource_id,
240 &request.command,
241 idem_key,
242 )
243 });
244
245 if let Some(ref composed_key) = composed_idempotency_key {
247 if let Some(existing_id) = self.check_idempotency(composed_key).await? {
248 let status = self
250 .command_registry
251 .get_command_status(&existing_id)
252 .await?;
253 if let Some(s) = status {
254 return Ok(CreateCommandResponse {
255 command_id: existing_id,
256 state: s.state,
257 storage_upload: None,
258 inline_allowed_up_to: self.inline_max_bytes as u64,
259 next: "poll".to_string(),
260 });
261 }
262 }
263 }
264
265 let (initial_state, request_size_bytes) = match &request.params {
267 BodySpec::Inline { inline_base64 } => {
268 let size = inline_base64.len() as u64;
269 (CommandState::Pending, Some(size))
270 }
271 BodySpec::Storage { size, .. } => {
272 if size.unwrap_or(0) > self.inline_max_bytes as u64 {
273 (CommandState::PendingUpload, *size)
274 } else {
275 (CommandState::Pending, *size)
276 }
277 }
278 };
279
280 let metadata = self
282 .command_registry
283 .create_command(
284 &request.deployment_id,
285 &request.command,
286 &resolved_target,
287 initial_state,
288 request.deadline,
289 request_size_bytes,
290 )
291 .await?;
292
293 let command_id = metadata.command_id;
294 let delivery_mode = metadata.delivery_mode;
295
296 if let Some(ref composed_key) = composed_idempotency_key {
303 if let Some(winner_id) = self.store_idempotency(composed_key, &command_id).await? {
304 let _ = self
305 .command_registry
306 .complete_command(
307 &command_id,
308 CommandState::Failed,
309 Utc::now(),
310 None,
311 Some(serde_json::json!({
312 "code": "IDEMPOTENT_DUPLICATE",
313 "message": format!(
314 "Superseded by concurrent create '{}' with the same idempotency key",
315 winner_id
316 ),
317 })),
318 )
319 .await?;
320 let status = self.command_registry.get_command_status(&winner_id).await?;
321 let state = status.map(|s| s.state).unwrap_or(CommandState::Pending);
322 return Ok(CreateCommandResponse {
323 command_id: winner_id,
324 state,
325 storage_upload: None,
326 inline_allowed_up_to: self.inline_max_bytes as u64,
327 next: "poll".to_string(),
328 });
329 }
330 }
331
332 self.store_params(&command_id, &request.params).await?;
334
335 let storage_upload = if initial_state == CommandState::PendingUpload {
337 Some(self.generate_params_upload(&command_id).await?)
338 } else {
339 None
340 };
341
342 let (final_state, next_action) = if initial_state == CommandState::Pending {
344 match delivery_mode {
345 CommandDeliveryMode::Push => {
346 let state = self
348 .dispatch_command_push(&command_id, &request.deployment_id)
349 .await?;
350 (state, "poll")
351 }
352 CommandDeliveryMode::Pull => {
353 self.create_pending_index(
356 &request.deployment_id,
357 &metadata.target.resource_id,
358 &command_id,
359 )
360 .await?;
361 debug!("Command {} ready for target-scoped lease", command_id);
362 (CommandState::Pending, "poll")
363 }
364 }
365 } else {
366 (initial_state, "upload")
368 };
369
370 if let Some(deadline) = request.deadline {
372 self.create_deadline_index(&command_id, deadline).await?;
373 }
374
375 Ok(CreateCommandResponse {
376 command_id,
377 state: final_state,
378 storage_upload,
379 inline_allowed_up_to: self.inline_max_bytes as u64,
380 next: next_action.to_string(),
381 })
382 }
383
384 pub async fn upload_complete(
386 &self,
387 command_id: &str,
388 upload_request: UploadCompleteRequest,
389 ) -> Result<UploadCompleteResponse> {
390 let status = self
392 .command_registry
393 .get_command_status(command_id)
394 .await?
395 .ok_or_else(|| {
396 AlienError::new(ErrorData::CommandNotFound {
397 command_id: command_id.to_string(),
398 })
399 })?;
400
401 if status.state != CommandState::PendingUpload {
403 return Err(AlienError::new(ErrorData::InvalidStateTransition {
404 from: status.state.as_ref().to_string(),
405 to: CommandState::Pending.as_ref().to_string(),
406 }));
407 }
408
409 let storage_get_request = self.generate_storage_get_request(command_id).await?;
411 let params = BodySpec::Storage {
412 size: Some(upload_request.size),
413 storage_get_request: Some(storage_get_request),
414 storage_put_used: None,
415 };
416 self.store_params(command_id, ¶ms).await?;
417
418 let transitioned = self
420 .command_registry
421 .update_command_state(command_id, CommandState::Pending, None, None, None, None)
422 .await?;
423 if !transitioned {
424 let current_state = self
425 .command_registry
426 .get_command_status(command_id)
427 .await?
428 .map(|current| current.state)
429 .unwrap_or(status.state);
430 return Err(AlienError::new(ErrorData::InvalidStateTransition {
431 from: current_state.as_ref().to_string(),
432 to: CommandState::Pending.as_ref().to_string(),
433 }));
434 }
435
436 let metadata = self
438 .command_registry
439 .get_command_metadata(command_id)
440 .await?
441 .ok_or_else(|| {
442 AlienError::new(ErrorData::CommandNotFound {
443 command_id: command_id.to_string(),
444 })
445 })?;
446
447 let final_state = match metadata.delivery_mode {
448 CommandDeliveryMode::Push => {
449 self.dispatch_command_push(command_id, &status.deployment_id)
450 .await?
451 }
452 CommandDeliveryMode::Pull => {
453 self.create_pending_index(
454 &status.deployment_id,
455 &metadata.target.resource_id,
456 command_id,
457 )
458 .await?;
459 debug!(
460 "Command {} ready for pull after upload (target will poll)",
461 command_id
462 );
463 CommandState::Pending
464 }
465 };
466
467 Ok(UploadCompleteResponse {
468 command_id: command_id.to_string(),
469 state: final_state,
470 })
471 }
472
473 pub async fn get_command_status(&self, command_id: &str) -> Result<CommandStatusResponse> {
477 let status = self
479 .command_registry
480 .get_command_status(command_id)
481 .await?
482 .ok_or_else(|| {
483 AlienError::new(ErrorData::CommandNotFound {
484 command_id: command_id.to_string(),
485 })
486 })?;
487
488 if let Some(deadline) = status.deadline {
490 if Utc::now() > deadline && !status.state.is_terminal() {
491 let won = self
496 .command_registry
497 .complete_command(command_id, CommandState::Expired, Utc::now(), None, None)
498 .await?;
499 if won {
500 self.delete_pending_index(
502 &status.deployment_id,
503 &status.target.resource_id,
504 command_id,
505 )
506 .await?;
507
508 return Ok(CommandStatusResponse {
510 command_id: command_id.to_string(),
511 state: CommandState::Expired,
512 attempt: status.attempt,
513 target: status.target,
514 response: None,
515 });
516 }
517 let status = self
520 .command_registry
521 .get_command_status(command_id)
522 .await?
523 .ok_or_else(|| {
524 AlienError::new(ErrorData::CommandNotFound {
525 command_id: command_id.to_string(),
526 })
527 })?;
528 let response = if status.state.is_terminal() {
529 self.get_response(command_id).await?
530 } else {
531 None
532 };
533 return Ok(CommandStatusResponse {
534 command_id: command_id.to_string(),
535 state: status.state,
536 attempt: status.attempt,
537 target: status.target,
538 response,
539 });
540 }
541 }
542
543 let response = if status.state.is_terminal() {
545 self.get_response(command_id).await?
546 } else {
547 None
548 };
549
550 Ok(CommandStatusResponse {
551 command_id: command_id.to_string(),
552 state: status.state,
553 attempt: status.attempt,
554 target: status.target,
555 response,
556 })
557 }
558
559 pub async fn submit_command_response(
563 &self,
564 command_id: &str,
565 mut response: CommandResponse,
566 ) -> Result<()> {
567 let status = self
569 .command_registry
570 .get_command_status(command_id)
571 .await?
572 .ok_or_else(|| {
573 AlienError::new(ErrorData::CommandNotFound {
574 command_id: command_id.to_string(),
575 })
576 })?;
577
578 if status.state.is_terminal() {
580 debug!(
581 "Ignoring duplicate response for terminal command {}",
582 command_id
583 );
584 return Ok(());
585 }
586
587 if status.state != CommandState::Dispatched {
589 return Err(AlienError::new(ErrorData::InvalidStateTransition {
590 from: status.state.as_ref().to_string(),
591 to: CommandState::Succeeded.as_ref().to_string(),
592 }));
593 }
594
595 if let CommandResponse::Success {
597 response: ref mut body,
598 } = response
599 {
600 if let BodySpec::Storage {
601 size,
602 storage_get_request,
603 storage_put_used,
604 } = body
605 {
606 if storage_get_request.is_none() && storage_put_used.unwrap_or(false) {
607 let get_request = self
608 .generate_response_storage_get_request(command_id)
609 .await?;
610 *body = BodySpec::Storage {
611 size: *size,
612 storage_get_request: Some(get_request),
613 storage_put_used: *storage_put_used,
614 };
615 }
616 }
617 }
618
619 self.store_response(command_id, &response).await?;
621
622 let (new_state, error) = if response.is_success() {
631 (CommandState::Succeeded, None)
632 } else if let CommandResponse::Error { code, message, .. } = &response {
633 (
634 CommandState::Failed,
635 Some(serde_json::json!({ "code": code, "message": message })),
636 )
637 } else {
638 (CommandState::Failed, None)
639 };
640
641 let response_size = match &response {
642 CommandResponse::Success {
643 response: BodySpec::Inline { inline_base64 },
644 } => Some(inline_base64.len() as u64),
645 CommandResponse::Success {
646 response: BodySpec::Storage { size, .. },
647 } => *size,
648 _ => None,
649 };
650
651 let won = self
661 .command_registry
662 .complete_command(command_id, new_state, Utc::now(), response_size, error)
663 .await?;
664 if !won {
665 debug!(
666 "Ignoring duplicate response for command {} (lost the terminal transition race)",
667 command_id
668 );
669 return Ok(());
670 }
671 self.store_response(command_id, &response).await?;
672
673 if let Err(e) = self.delete_lease(command_id).await {
678 warn!(
679 command_id,
680 error = %e,
681 "Failed to clean up lease after terminal response; will be reaped on next lease scan"
682 );
683 }
684
685 if let Err(e) = self
688 .delete_pending_index(
689 &status.deployment_id,
690 &status.target.resource_id,
691 command_id,
692 )
693 .await
694 {
695 warn!(
696 command_id,
697 error = %e,
698 "Failed to clean up pending index after terminal response; will be reaped on next lease scan"
699 );
700 }
701
702 info!(
703 "Command {} completed with state {:?}",
704 command_id, new_state
705 );
706 Ok(())
707 }
708
709 pub async fn acquire_lease(
713 &self,
714 deployment_id: &str,
715 lease_request: &LeaseRequest,
716 ) -> Result<LeaseResponse> {
717 let mut leases = Vec::new();
718
719 let target_prefix = format!(
722 "target:{}:{}:pending:",
723 deployment_id, lease_request.target.resource_id
724 );
725 let scan_result = self
726 .kv
727 .scan_prefix(&target_prefix, Some(lease_request.max_leases * 2), None)
728 .await
729 .into_alien_error()
730 .context(ErrorData::KvOperationFailed {
731 operation: "scan_prefix".to_string(),
732 key: target_prefix.clone(),
733 message: "Failed to scan for pending commands".to_string(),
734 })?;
735
736 for entry in scan_result.items {
737 let index_key = entry.key;
738 if leases.len() >= lease_request.max_leases {
739 break;
740 }
741
742 let command_id = self.extract_command_id_from_index_key(&index_key)?;
743
744 let lease_id = format!("lease_{}", Uuid::new_v4());
746 let lease_duration = Duration::from_secs(lease_request.lease_seconds);
747 let expires_at =
748 Utc::now() + chrono::Duration::seconds(lease_request.lease_seconds as i64);
749
750 let lease_data = LeaseData {
751 lease_id: lease_id.clone(),
752 acquired_at: Utc::now(),
753 expires_at,
754 owner: deployment_id.to_string(),
755 };
756
757 let lease_key = format!("cmd:{}:lease", command_id);
758 let lease_value = serde_json::to_vec(&lease_data).into_alien_error().context(
759 ErrorData::SerializationFailed {
760 message: "Failed to serialize lease data".to_string(),
761 data_type: Some("LeaseData".to_string()),
762 },
763 )?;
764
765 let options = Some(PutOptions {
766 ttl: Some(lease_duration),
767 condition: PutCondition::Absent,
768 });
769
770 let success = self
771 .kv
772 .put(&lease_key, lease_value, options)
773 .await
774 .context(ErrorData::KvOperationFailed {
775 operation: "put".to_string(),
776 key: lease_key.clone(),
777 message: "Failed to create lease".to_string(),
778 })?;
779
780 if !success {
781 continue;
783 }
784
785 let reverse_key = format!("lease:{}", lease_id);
790 self.kv
791 .put(
792 &reverse_key,
793 command_id.as_bytes().to_vec(),
794 Some(PutOptions {
795 ttl: Some(lease_duration),
796 condition: PutCondition::None,
797 }),
798 )
799 .await
800 .context(ErrorData::KvOperationFailed {
801 operation: "put".to_string(),
802 key: reverse_key,
803 message: "Failed to create lease reverse index".to_string(),
804 })?;
805
806 let mut metadata = match self
808 .command_registry
809 .get_command_metadata(&command_id)
810 .await?
811 {
812 Some(m) => m,
813 None => {
814 self.delete_lease(&command_id).await?;
816 let _ = self.kv.delete(&index_key, None).await;
817 continue;
818 }
819 };
820
821 if metadata.state == CommandState::Dispatched {
829 self.command_registry.increment_attempt(&command_id).await?;
830 metadata.attempt += 1;
831 }
832
833 if metadata.target != lease_request.target {
841 self.delete_lease(&command_id).await?;
842 return Err(AlienError::new(ErrorData::Other {
843 message: format!(
844 "Pending index corruption: command '{}' is indexed under target '{}' \
845 but the registry says it belongs to target '{}' — refusing to deliver",
846 command_id, lease_request.target.resource_id, metadata.target.resource_id,
847 ),
848 }));
849 }
850
851 if metadata.state.is_terminal() {
853 self.delete_lease(&command_id).await?;
855 let _ = self.kv.delete(&index_key, None).await;
856 continue;
857 }
858
859 if let Some(deadline) = metadata.deadline {
862 if Utc::now() > deadline {
863 let _ = self
864 .command_registry
865 .complete_command(
866 &command_id,
867 CommandState::Expired,
868 Utc::now(),
869 None,
870 None,
871 )
872 .await?;
873 self.delete_lease(&command_id).await?;
874 let _ = self.kv.delete(&index_key, None).await;
875 continue;
876 }
877 }
878
879 let params = match self.get_params(&command_id).await? {
881 Some(p) => p,
882 None => {
883 self.delete_lease(&command_id).await?;
885 continue;
886 }
887 };
888
889 let dispatched = self
894 .command_registry
895 .mark_dispatched_if_not_terminal(&command_id, Utc::now())
896 .await?;
897 if !dispatched {
898 debug!(
899 command_id = %command_id,
900 "Command turned terminal while leasing; releasing the lease"
901 );
902 self.delete_lease(&command_id).await?;
903 let _ = self.kv.delete(&index_key, None).await;
904 continue;
905 }
906
907 let mut envelope = self.build_envelope(&command_id, &metadata, params).await?;
916 Self::relativize_manager_urls(&mut envelope, &self.base_url);
917
918 leases.push(LeaseInfo {
919 lease_id,
920 lease_expires_at: expires_at,
921 command_id: command_id.clone(),
922 attempt: metadata.attempt,
923 envelope,
924 });
925 }
926
927 Ok(LeaseResponse { leases })
928 }
929
930 fn relativize_manager_urls(envelope: &mut Envelope, base_url: &str) {
935 let Ok(mut lease_endpoint) = reqwest::Url::parse(base_url) else {
936 return;
939 };
940 let Ok(mut segments) = lease_endpoint.path_segments_mut() else {
941 return;
942 };
943 segments.pop_if_empty().push("commands").push("leases");
944 drop(segments);
945 lease_endpoint.set_query(None);
946 lease_endpoint.set_fragment(None);
947
948 let relativize = |target: &mut String| {
949 let Ok(mut target_url) = reqwest::Url::parse(target.as_str()) else {
950 return;
951 };
952 let suffix = target
953 .find(['?', '#'])
954 .map(|index| target[index..].to_string())
955 .unwrap_or_default();
956 target_url.set_query(None);
957 target_url.set_fragment(None);
958 if let Some(relative) = lease_endpoint.make_relative(&target_url) {
959 *target = format!("{relative}{suffix}");
960 }
961 };
962
963 relativize(&mut envelope.response_handling.submit_response_url);
964 if let alien_core::presigned::PresignedRequestBackend::Http { url, .. } =
965 &mut envelope.response_handling.storage_upload_request.backend
966 {
967 relativize(url);
968 }
969 if let BodySpec::Storage {
970 storage_get_request: Some(request),
971 ..
972 } = &mut envelope.params
973 {
974 if let alien_core::presigned::PresignedRequestBackend::Http { url, .. } =
975 &mut request.backend
976 {
977 relativize(url);
978 }
979 }
980 }
981
982 pub async fn release_lease(&self, command_id: &str, lease_id: &str) -> Result<()> {
986 let lease_key = format!("cmd:{}:lease", command_id);
987
988 if let Ok(Some(lease_data)) = self.kv.get(&lease_key).await {
990 let lease: LeaseData = serde_json::from_slice(&lease_data.value)
991 .into_alien_error()
992 .context(ErrorData::SerializationFailed {
993 message: "Failed to deserialize lease data".to_string(),
994 data_type: Some("LeaseData".to_string()),
995 })?;
996
997 if lease.lease_id != lease_id {
998 return Err(AlienError::new(ErrorData::LeaseNotFound {
999 lease_id: lease_id.to_string(),
1000 }));
1001 }
1002
1003 self.delete_lease(command_id).await?;
1005 let _ = self.kv.delete(&format!("lease:{}", lease_id), None).await;
1006
1007 let released = self
1010 .command_registry
1011 .update_command_state(command_id, CommandState::Pending, None, None, None, None)
1012 .await?;
1013 if released {
1014 self.command_registry.increment_attempt(command_id).await?;
1017 }
1018
1019 debug!(
1021 released,
1022 "Lease {} released for command {}", lease_id, command_id
1023 );
1024 }
1025
1026 Ok(())
1027 }
1028
1029 pub async fn get_command_deployment_id(&self, command_id: &str) -> Result<Option<String>> {
1034 let status = self.command_registry.get_command_status(command_id).await?;
1035 Ok(status.map(|s| s.deployment_id))
1036 }
1037
1038 pub async fn get_command_status_record(
1040 &self,
1041 command_id: &str,
1042 ) -> Result<Option<CommandStatus>> {
1043 self.command_registry.get_command_status(command_id).await
1044 }
1045
1046 pub async fn get_command_access_context(
1048 &self,
1049 command_id: &str,
1050 ) -> Result<Option<CommandAccessContext>> {
1051 self.command_registry
1052 .get_command_access_context(command_id)
1053 .await
1054 }
1055
1056 pub async fn get_lease_owner(&self, lease_id: &str) -> Result<Option<(String, String)>> {
1064 let reverse_key = format!("lease:{}", lease_id);
1065 let Some(command_id_bytes) =
1066 self.kv
1067 .get(&reverse_key)
1068 .await
1069 .context(ErrorData::KvOperationFailed {
1070 operation: "get".to_string(),
1071 key: reverse_key.clone(),
1072 message: "Failed to look up lease reverse index".to_string(),
1073 })?
1074 else {
1075 return Ok(None);
1076 };
1077 let command_id = String::from_utf8(command_id_bytes.value).map_err(|_| {
1078 AlienError::new(ErrorData::Other {
1079 message: format!("Lease reverse index '{}' is not valid UTF-8", reverse_key),
1080 })
1081 })?;
1082
1083 let lease_key = format!("cmd:{}:lease", command_id);
1084 let Some(lease_data) =
1085 self.kv
1086 .get(&lease_key)
1087 .await
1088 .context(ErrorData::KvOperationFailed {
1089 operation: "get".to_string(),
1090 key: lease_key,
1091 message: "Failed to look up lease".to_string(),
1092 })?
1093 else {
1094 return Ok(None);
1095 };
1096 let lease: LeaseData = serde_json::from_slice(&lease_data.value)
1097 .into_alien_error()
1098 .context(ErrorData::SerializationFailed {
1099 message: "Failed to deserialize lease data".to_string(),
1100 data_type: Some("LeaseData".to_string()),
1101 })?;
1102 if lease.lease_id != lease_id {
1103 return Ok(None);
1104 }
1105
1106 Ok(Some((command_id, lease.owner)))
1107 }
1108
1109 pub async fn release_lease_by_id(&self, lease_id: &str) -> Result<()> {
1111 match self.get_lease_owner(lease_id).await? {
1112 Some((command_id, _owner)) => self.release_lease(&command_id, lease_id).await,
1113 None => Err(AlienError::new(ErrorData::LeaseNotFound {
1114 lease_id: lease_id.to_string(),
1115 })),
1116 }
1117 }
1118
1119 async fn validate_create_command(&self, request: &CreateCommandRequest) -> Result<()> {
1124 if request.command.is_empty() {
1125 return Err(AlienError::new(ErrorData::InvalidCommand {
1126 message: "Command name cannot be empty".to_string(),
1127 }));
1128 }
1129
1130 validate_command_name(&request.command)?;
1138
1139 if request.deployment_id.is_empty() {
1140 return Err(AlienError::new(ErrorData::InvalidCommand {
1141 message: "Deployment ID cannot be empty".to_string(),
1142 }));
1143 }
1144
1145 if let Some(deadline) = request.deadline {
1146 if deadline <= Utc::now() {
1147 return Err(AlienError::new(ErrorData::InvalidCommand {
1148 message: "Deadline must be in the future".to_string(),
1149 }));
1150 }
1151 }
1152
1153 Ok(())
1154 }
1155
1156 fn compose_idempotency_key(
1164 deployment_id: &str,
1165 target_resource_id: &str,
1166 command_name: &str,
1167 idem_key: &str,
1168 ) -> String {
1169 debug_assert!(
1179 !target_resource_id.contains(':'),
1180 "target_resource_id must be ':'-free before key composition: {target_resource_id}"
1181 );
1182 format!(
1183 "{}:{}:{}:{}",
1184 deployment_id, target_resource_id, command_name, idem_key
1185 )
1186 }
1187
1188 async fn check_idempotency(&self, idem_key: &str) -> Result<Option<String>> {
1189 let key = format!("idem:{}", idem_key);
1190 if let Some(data) = self
1191 .kv
1192 .get(&key)
1193 .await
1194 .context(ErrorData::KvOperationFailed {
1195 operation: "get".to_string(),
1196 key: key.clone(),
1197 message: "Failed to check idempotency".to_string(),
1198 })?
1199 {
1200 let command_id = String::from_utf8(data.value).into_alien_error().context(
1201 ErrorData::SerializationFailed {
1202 message: "Invalid idempotency data".to_string(),
1203 data_type: Some("String".to_string()),
1204 },
1205 )?;
1206 return Ok(Some(command_id));
1207 }
1208 Ok(None)
1209 }
1210
1211 async fn store_idempotency(&self, idem_key: &str, command_id: &str) -> Result<Option<String>> {
1219 let key = format!("idem:{}", idem_key);
1220 let ttl = Duration::from_secs(24 * 60 * 60); let won = self
1222 .kv
1223 .put(
1224 &key,
1225 command_id.as_bytes().to_vec(),
1226 Some(PutOptions {
1227 ttl: Some(ttl),
1228 condition: PutCondition::Absent,
1229 }),
1230 )
1231 .await
1232 .context(ErrorData::KvOperationFailed {
1233 operation: "put".to_string(),
1234 key: key.clone(),
1235 message: "Failed to store idempotency".to_string(),
1236 })?;
1237 if won {
1238 return Ok(None);
1239 }
1240 match self.check_idempotency(idem_key).await? {
1244 Some(winner_id) => Ok(Some(winner_id)),
1245 None => Err(AlienError::new(ErrorData::Other {
1246 message: format!(
1247 "Idempotency key '{}' was concurrently claimed but has no winner entry",
1248 key
1249 ),
1250 })),
1251 }
1252 }
1253
1254 pub async fn store_params(&self, command_id: &str, params: &BodySpec) -> Result<()> {
1257 let key = format!("cmd:{}:params", command_id);
1258
1259 let data = CommandParamsData {
1261 params: params.clone(),
1262 };
1263 let value = serde_json::to_vec(&data).into_alien_error().context(
1264 ErrorData::SerializationFailed {
1265 message: "Failed to serialize params".to_string(),
1266 data_type: Some("CommandParamsData".to_string()),
1267 },
1268 )?;
1269
1270 if value.len() <= KV_VALUE_THRESHOLD {
1272 self.kv
1273 .put(&key, value, None)
1274 .await
1275 .context(ErrorData::KvOperationFailed {
1276 operation: "put".to_string(),
1277 key: key.clone(),
1278 message: "Failed to store params".to_string(),
1279 })?;
1280 return Ok(());
1281 }
1282
1283 if let BodySpec::Inline { inline_base64 } = params {
1285 let raw_bytes = general_purpose::STANDARD
1286 .decode(inline_base64)
1287 .into_alien_error()
1288 .context(ErrorData::SerializationFailed {
1289 message: "Failed to decode inline base64 params for auto-promotion".to_string(),
1290 data_type: Some("base64".to_string()),
1291 })?;
1292
1293 let raw_len = raw_bytes.len() as u64;
1294 let blob_path = StoragePath::from(format!("arc/commands/{}/params", command_id));
1295
1296 self.storage
1297 .put(&blob_path, Bytes::from(raw_bytes).into())
1298 .await
1299 .into_alien_error()
1300 .context(ErrorData::StorageOperationFailed {
1301 message: "Failed to auto-promote params to blob storage".to_string(),
1302 operation: Some("put".to_string()),
1303 path: Some(blob_path.to_string()),
1304 })?;
1305
1306 debug!(
1307 "Auto-promoted params for command {} to blob ({} bytes raw)",
1308 command_id, raw_len
1309 );
1310
1311 let promoted = CommandParamsData {
1313 params: BodySpec::Storage {
1314 size: Some(raw_len),
1315 storage_get_request: None,
1316 storage_put_used: Some(true),
1317 },
1318 };
1319 let promoted_value = serde_json::to_vec(&promoted).into_alien_error().context(
1320 ErrorData::SerializationFailed {
1321 message: "Failed to serialize promoted params reference".to_string(),
1322 data_type: Some("CommandParamsData".to_string()),
1323 },
1324 )?;
1325 self.kv.put(&key, promoted_value, None).await.context(
1326 ErrorData::KvOperationFailed {
1327 operation: "put".to_string(),
1328 key: key.clone(),
1329 message: "Failed to store promoted params reference".to_string(),
1330 },
1331 )?;
1332 return Ok(());
1333 }
1334
1335 self.kv
1337 .put(&key, value, None)
1338 .await
1339 .context(ErrorData::KvOperationFailed {
1340 operation: "put".to_string(),
1341 key: key.clone(),
1342 message: "Failed to store params".to_string(),
1343 })?;
1344 Ok(())
1345 }
1346
1347 pub async fn get_params(&self, command_id: &str) -> Result<Option<BodySpec>> {
1348 let key = format!("cmd:{}:params", command_id);
1349 if let Some(value) = self
1350 .kv
1351 .get(&key)
1352 .await
1353 .context(ErrorData::KvOperationFailed {
1354 operation: "get".to_string(),
1355 key: key.clone(),
1356 message: "Failed to get params".to_string(),
1357 })?
1358 {
1359 let data: CommandParamsData = serde_json::from_slice(&value.value)
1360 .into_alien_error()
1361 .context(ErrorData::SerializationFailed {
1362 message: "Failed to deserialize params".to_string(),
1363 data_type: Some("CommandParamsData".to_string()),
1364 })?;
1365 return Ok(Some(data.params));
1366 }
1367 Ok(None)
1368 }
1369
1370 pub async fn store_response(&self, command_id: &str, response: &CommandResponse) -> Result<()> {
1373 let key = format!("cmd:{}:response", command_id);
1374 let data = CommandResponseData {
1375 response: response.clone(),
1376 };
1377 let value = serde_json::to_vec(&data).into_alien_error().context(
1378 ErrorData::SerializationFailed {
1379 message: "Failed to serialize response".to_string(),
1380 data_type: Some("CommandResponseData".to_string()),
1381 },
1382 )?;
1383
1384 if value.len() <= KV_VALUE_THRESHOLD {
1386 self.kv
1387 .put(&key, value, None)
1388 .await
1389 .context(ErrorData::KvOperationFailed {
1390 operation: "put".to_string(),
1391 key: key.clone(),
1392 message: "Failed to store response".to_string(),
1393 })?;
1394 return Ok(());
1395 }
1396
1397 if let CommandResponse::Success {
1399 response: BodySpec::Inline { inline_base64 },
1400 } = response
1401 {
1402 let raw_bytes = general_purpose::STANDARD
1403 .decode(inline_base64)
1404 .into_alien_error()
1405 .context(ErrorData::SerializationFailed {
1406 message: "Failed to decode inline base64 response for auto-promotion"
1407 .to_string(),
1408 data_type: Some("base64".to_string()),
1409 })?;
1410
1411 let raw_len = raw_bytes.len() as u64;
1412 let blob_path = StoragePath::from(format!("arc/commands/{}/response", command_id));
1413
1414 self.storage
1415 .put(&blob_path, Bytes::from(raw_bytes).into())
1416 .await
1417 .into_alien_error()
1418 .context(ErrorData::StorageOperationFailed {
1419 message: "Failed to auto-promote response to blob storage".to_string(),
1420 operation: Some("put".to_string()),
1421 path: Some(blob_path.to_string()),
1422 })?;
1423
1424 let get_request = self
1426 .generate_response_storage_get_request(command_id)
1427 .await?;
1428
1429 debug!(
1430 "Auto-promoted response for command {} to blob ({} bytes raw)",
1431 command_id, raw_len
1432 );
1433
1434 let promoted = CommandResponseData {
1436 response: CommandResponse::Success {
1437 response: BodySpec::Storage {
1438 size: Some(raw_len),
1439 storage_get_request: Some(get_request),
1440 storage_put_used: Some(true),
1441 },
1442 },
1443 };
1444 let promoted_value = serde_json::to_vec(&promoted).into_alien_error().context(
1445 ErrorData::SerializationFailed {
1446 message: "Failed to serialize promoted response reference".to_string(),
1447 data_type: Some("CommandResponseData".to_string()),
1448 },
1449 )?;
1450 self.kv.put(&key, promoted_value, None).await.context(
1451 ErrorData::KvOperationFailed {
1452 operation: "put".to_string(),
1453 key: key.clone(),
1454 message: "Failed to store promoted response reference".to_string(),
1455 },
1456 )?;
1457 return Ok(());
1458 }
1459
1460 self.kv
1462 .put(&key, value, None)
1463 .await
1464 .context(ErrorData::KvOperationFailed {
1465 operation: "put".to_string(),
1466 key: key.clone(),
1467 message: "Failed to store response".to_string(),
1468 })?;
1469 Ok(())
1470 }
1471
1472 pub async fn get_response(&self, command_id: &str) -> Result<Option<CommandResponse>> {
1473 let key = format!("cmd:{}:response", command_id);
1474 if let Some(value) = self
1475 .kv
1476 .get(&key)
1477 .await
1478 .context(ErrorData::KvOperationFailed {
1479 operation: "get".to_string(),
1480 key: key.clone(),
1481 message: "Failed to get response".to_string(),
1482 })?
1483 {
1484 let data: CommandResponseData = serde_json::from_slice(&value.value)
1485 .into_alien_error()
1486 .context(ErrorData::SerializationFailed {
1487 message: "Failed to deserialize response".to_string(),
1488 data_type: Some("CommandResponseData".to_string()),
1489 })?;
1490 return Ok(Some(data.response));
1491 }
1492 Ok(None)
1493 }
1494
1495 async fn create_pending_index(
1498 &self,
1499 deployment_id: &str,
1500 target_resource_id: &str,
1501 command_id: &str,
1502 ) -> Result<()> {
1503 debug_assert!(
1507 !target_resource_id.contains(':'),
1508 "target_resource_id must be ':'-free in the pending index: {target_resource_id}"
1509 );
1510 let timestamp = Utc::now().timestamp_nanos_opt().unwrap_or(0);
1511 let key = format!(
1512 "target:{}:{}:pending:{}:{}",
1513 deployment_id, target_resource_id, timestamp, command_id
1514 );
1515
1516 self.kv
1518 .put(&key, vec![], None)
1519 .await
1520 .context(ErrorData::KvOperationFailed {
1521 operation: "put".to_string(),
1522 key: key.clone(),
1523 message: "Failed to create pending index".to_string(),
1524 })?;
1525 Ok(())
1526 }
1527
1528 async fn delete_pending_index(
1529 &self,
1530 deployment_id: &str,
1531 target_resource_id: &str,
1532 command_id: &str,
1533 ) -> Result<()> {
1534 let prefix = format!("target:{}:{}:pending:", deployment_id, target_resource_id);
1536 let scan_result = self
1537 .kv
1538 .scan_prefix(&prefix, Some(100), None)
1539 .await
1540 .into_alien_error()
1541 .context(ErrorData::KvOperationFailed {
1542 operation: "scan_prefix".to_string(),
1543 key: prefix.clone(),
1544 message: "Failed to scan pending index".to_string(),
1545 })?;
1546
1547 for entry in scan_result.items {
1548 if entry.key.ends_with(&format!(":{}", command_id)) {
1549 let _ = self.kv.delete(&entry.key, None).await;
1550 break;
1551 }
1552 }
1553 Ok(())
1554 }
1555
1556 async fn delete_lease(&self, command_id: &str) -> Result<()> {
1559 let key = format!("cmd:{}:lease", command_id);
1560 let _ = self.kv.delete(&key, None).await;
1561 Ok(())
1562 }
1563
1564 pub async fn reap_expired_commands(&self) -> Result<u32> {
1576 let now = Utc::now();
1577 let mut expired = 0u32;
1578 let mut cursor: Option<String> = None;
1579 for _ in 0..64 {
1584 let scan = self
1585 .kv
1586 .scan_prefix("deadline:", Some(256), cursor.clone())
1587 .await
1588 .into_alien_error()
1589 .context(ErrorData::KvOperationFailed {
1590 operation: "scan_prefix".to_string(),
1591 key: "deadline:".to_string(),
1592 message: "Failed to scan the deadline index".to_string(),
1593 })?;
1594 let next_cursor = scan.next_cursor.clone();
1595 for entry in scan.items {
1596 let Ok(data) = serde_json::from_slice::<DeadlineIndexData>(&entry.value) else {
1597 warn!(key = %entry.key, "Unparseable deadline index entry; deleting");
1598 let _ = self.kv.delete(&entry.key, None).await;
1599 continue;
1600 };
1601 if data.deadline > now {
1602 continue;
1605 }
1606
1607 let status = self
1608 .command_registry
1609 .get_command_status(&data.command_id)
1610 .await?;
1611 match status {
1612 None => {
1613 let _ = self.kv.delete(&entry.key, None).await;
1614 }
1615 Some(status) if status.state.is_terminal() => {
1616 let _ = self.kv.delete(&entry.key, None).await;
1617 }
1618 Some(status) => {
1619 let won = self
1620 .command_registry
1621 .complete_command(
1622 &data.command_id,
1623 CommandState::Expired,
1624 now,
1625 None,
1626 Some(serde_json::json!({
1627 "code": "COMMAND_EXPIRED",
1628 "message": format!("Deadline {} elapsed", data.deadline.to_rfc3339()),
1629 })),
1630 )
1631 .await?;
1632 if won {
1633 expired += 1;
1634 info!(command_id = %data.command_id, "Expired overdue command");
1635 let _ = self.delete_lease(&data.command_id).await;
1636 let _ = self
1637 .delete_pending_index(
1638 &status.deployment_id,
1639 &status.target.resource_id,
1640 &data.command_id,
1641 )
1642 .await;
1643 }
1644 let _ = self.kv.delete(&entry.key, None).await;
1645 }
1646 }
1647 }
1648 match next_cursor {
1649 Some(next) => cursor = Some(next),
1650 None => break,
1651 }
1652 }
1653 Ok(expired)
1654 }
1655
1656 async fn create_deadline_index(&self, command_id: &str, deadline: DateTime<Utc>) -> Result<()> {
1659 let key = format!(
1660 "deadline:{}:{}",
1661 deadline.timestamp_nanos_opt().unwrap_or(0),
1662 command_id
1663 );
1664
1665 let data = DeadlineIndexData {
1666 command_id: command_id.to_string(),
1667 deadline,
1668 };
1669 let value = serde_json::to_vec(&data).into_alien_error().context(
1670 ErrorData::SerializationFailed {
1671 message: "Failed to serialize deadline index".to_string(),
1672 data_type: Some("DeadlineIndexData".to_string()),
1673 },
1674 )?;
1675
1676 const DEADLINE_INDEX_GRACE: chrono::Duration = chrono::Duration::days(7);
1683 let ttl = deadline
1684 .signed_duration_since(Utc::now())
1685 .checked_add(&DEADLINE_INDEX_GRACE)
1686 .unwrap_or(DEADLINE_INDEX_GRACE);
1687 let options = (ttl.num_seconds() > 0).then(|| PutOptions {
1688 ttl: Some(Duration::from_secs(ttl.num_seconds() as u64)),
1689 condition: PutCondition::None,
1690 });
1691
1692 self.kv
1693 .put(&key, value, options)
1694 .await
1695 .context(ErrorData::KvOperationFailed {
1696 operation: "put".to_string(),
1697 key: key.clone(),
1698 message: "Failed to create deadline index".to_string(),
1699 })?;
1700 Ok(())
1701 }
1702
1703 async fn dispatch_command_push(
1706 &self,
1707 command_id: &str,
1708 deployment_id: &str,
1709 ) -> Result<CommandState> {
1710 let metadata = self
1712 .command_registry
1713 .get_command_metadata(command_id)
1714 .await?
1715 .ok_or_else(|| {
1716 AlienError::new(ErrorData::CommandNotFound {
1717 command_id: command_id.to_string(),
1718 })
1719 })?;
1720
1721 let params = self.get_params(command_id).await?.ok_or_else(|| {
1723 AlienError::new(ErrorData::CommandNotFound {
1724 command_id: command_id.to_string(),
1725 })
1726 })?;
1727
1728 let envelope = self.build_envelope(command_id, &metadata, params).await?;
1730
1731 if !self
1737 .command_registry
1738 .mark_dispatched_if_not_terminal(command_id, Utc::now())
1739 .await?
1740 {
1741 return Ok(self
1742 .command_registry
1743 .get_command_status(command_id)
1744 .await?
1745 .map(|status| status.state)
1746 .unwrap_or(CommandState::Dispatched));
1747 }
1748
1749 if let Err(error) = self.command_dispatcher.dispatch(&envelope).await {
1757 if is_definite_dispatch_rejection(&error) {
1758 let delivery_failure = CommandResponse::error(
1759 "DELIVERY_FAILED",
1760 "Worker runtime did not accept command delivery",
1761 );
1762 self.submit_command_response(command_id, delivery_failure)
1763 .await?;
1764 warn!(
1765 command_id,
1766 deployment_id,
1767 error = %error,
1768 "Push dispatch was definitely rejected; command marked Failed"
1769 );
1770 return Ok(CommandState::Failed);
1771 }
1772
1773 let error = error.context(ErrorData::TransportDispatchFailed {
1774 message: "Failed to dispatch command".to_string(),
1775 transport_type: None,
1776 target: Some(deployment_id.to_string()),
1777 });
1778 warn!(
1779 command_id,
1780 deployment_id,
1781 error = %error,
1782 "Push dispatch acknowledgement failed; command remains Dispatched for a possible late response"
1783 );
1784 return Ok(CommandState::Dispatched);
1785 }
1786
1787 info!("Command {} dispatched via push", envelope.command_id);
1788 Ok(CommandState::Dispatched)
1789 }
1790
1791 async fn build_envelope(
1792 &self,
1793 command_id: &str,
1794 metadata: &CommandEnvelopeData,
1795 mut params: BodySpec,
1796 ) -> Result<Envelope> {
1797 let response_handling = self.create_response_handling(command_id).await?;
1798
1799 if let BodySpec::Storage { size, .. } = ¶ms {
1802 let raw_size = size.unwrap_or(0) as usize;
1803 if raw_size > 0 && raw_size <= self.inline_max_bytes {
1804 let blob_path = StoragePath::from(format!("arc/commands/{}/params", command_id));
1805 match self.storage.get(&blob_path).await {
1806 Ok(get_result) => match get_result.bytes().await {
1807 Ok(raw_bytes) => {
1808 params = BodySpec::inline(&raw_bytes);
1809 debug!(
1810 "Re-inlined params for command {} ({} bytes) into envelope",
1811 command_id, raw_size
1812 );
1813 }
1814 Err(e) => {
1815 debug!(
1816 "Failed to read blob bytes for re-inline (command {}), falling back to presigned URL: {}",
1817 command_id, e
1818 );
1819 }
1820 },
1821 Err(e) => {
1822 debug!(
1823 "Failed to read blob for re-inline (command {}), falling back to presigned URL: {}",
1824 command_id, e
1825 );
1826 }
1827 }
1828 }
1829 }
1830
1831 if let BodySpec::Storage {
1836 size,
1837 storage_get_request: _,
1838 storage_put_used,
1839 } = ¶ms
1840 {
1841 let get_request = self.generate_storage_get_request(command_id).await?;
1842 params = BodySpec::Storage {
1843 size: *size,
1844 storage_get_request: Some(get_request),
1845 storage_put_used: *storage_put_used,
1846 };
1847 }
1848
1849 Ok(Envelope::new(
1850 metadata.deployment_id.clone(),
1851 metadata.target.clone(),
1852 command_id.to_string(),
1853 metadata.attempt,
1854 metadata.deadline,
1855 metadata.command.clone(),
1856 params,
1857 response_handling,
1858 ))
1859 }
1860
1861 async fn create_response_handling(&self, command_id: &str) -> Result<ResponseHandling> {
1862 let upload_path = StoragePath::from(format!("arc/commands/{}/response", command_id));
1863 let expires_in = Duration::from_secs(Self::RESPONSE_CREDENTIAL_LIFETIME_SECS);
1864 let presigned = self
1865 .storage
1866 .presigned_put(&upload_path, expires_in)
1867 .await
1868 .context(ErrorData::StorageOperationFailed {
1869 message: "Failed to create response upload URL".to_string(),
1870 operation: Some("presigned_put".to_string()),
1871 path: Some(upload_path.to_string()),
1872 })?;
1873
1874 let (response_token, expires) = self.sign_response_url(command_id);
1875
1876 Ok(ResponseHandling {
1877 max_inline_bytes: self.inline_max_bytes as u64,
1878 submit_response_url: format!(
1879 "{}/commands/{}/response?response_token={}&expires={}",
1880 self.base_url.trim_end_matches('/'),
1881 command_id,
1882 response_token,
1883 expires,
1884 ),
1885 storage_upload_request: presigned,
1886 })
1887 }
1888
1889 async fn generate_params_upload(&self, command_id: &str) -> Result<StorageUpload> {
1890 let upload_path = StoragePath::from(format!("arc/commands/{}/params", command_id));
1891 let expires_in = Duration::from_secs(3600);
1892 let presigned = self
1893 .storage
1894 .presigned_put(&upload_path, expires_in)
1895 .await
1896 .into_alien_error()
1897 .context(ErrorData::StorageOperationFailed {
1898 message: "Failed to create presigned URL".to_string(),
1899 operation: Some("presigned_put".to_string()),
1900 path: Some(upload_path.to_string()),
1901 })?;
1902
1903 Ok(StorageUpload {
1904 put_request: presigned.clone(),
1905 expires_at: presigned.expiration,
1906 })
1907 }
1908
1909 async fn generate_storage_get_request(&self, command_id: &str) -> Result<PresignedRequest> {
1910 let path = StoragePath::from(format!("arc/commands/{}/params", command_id));
1911 let expires_in = Duration::from_secs(3600);
1912 self.storage.presigned_get(&path, expires_in).await.context(
1913 ErrorData::StorageOperationFailed {
1914 message: "Failed to create storage get request".to_string(),
1915 operation: Some("presigned_get".to_string()),
1916 path: Some(path.to_string()),
1917 },
1918 )
1919 }
1920
1921 async fn generate_response_storage_get_request(
1922 &self,
1923 command_id: &str,
1924 ) -> Result<PresignedRequest> {
1925 let path = StoragePath::from(format!("arc/commands/{}/response", command_id));
1926 let expires_in = Duration::from_secs(3600);
1927 self.storage.presigned_get(&path, expires_in).await.context(
1928 ErrorData::StorageOperationFailed {
1929 message: "Failed to create response storage get request".to_string(),
1930 operation: Some("presigned_get".to_string()),
1931 path: Some(path.to_string()),
1932 },
1933 )
1934 }
1935
1936 fn extract_command_id_from_index_key(&self, index_key: &str) -> Result<String> {
1937 index_key
1938 .split(':')
1939 .last()
1940 .ok_or_else(|| {
1941 AlienError::new(ErrorData::Other {
1942 message: format!("Invalid index key format: {}", index_key),
1943 })
1944 })
1945 .map(|s| s.to_string())
1946 }
1947}
1948
1949#[cfg(test)]
1950mod relative_url_tests {
1951 use super::*;
1952 use alien_core::presigned::PresignedOperation;
1953 use std::collections::HashMap;
1954
1955 fn http_request(url: &str, operation: PresignedOperation) -> PresignedRequest {
1956 PresignedRequest::new_http(
1957 url.to_string(),
1958 match operation {
1959 PresignedOperation::Get => "GET",
1960 PresignedOperation::Put => "PUT",
1961 PresignedOperation::Delete => "DELETE",
1962 }
1963 .to_string(),
1964 HashMap::new(),
1965 operation,
1966 "commands/test".to_string(),
1967 Utc::now() + chrono::Duration::minutes(5),
1968 )
1969 }
1970
1971 #[test]
1972 fn leased_manager_urls_are_relative_to_lease_endpoint() {
1973 let mut envelope = Envelope::new(
1974 "deployment",
1975 CommandTarget::new("daemon", CommandTargetType::Daemon),
1976 "command",
1977 1,
1978 None,
1979 "run",
1980 BodySpec::Storage {
1981 size: Some(2048),
1982 storage_get_request: Some(http_request(
1983 "http://manager.internal/storage/params?signature=params",
1984 PresignedOperation::Get,
1985 )),
1986 storage_put_used: Some(true),
1987 },
1988 ResponseHandling {
1989 max_inline_bytes: 1024,
1990 submit_response_url:
1991 "http://manager.internal/v1/commands/command/response?response_token=DoNotCanonicalize%2FValue&expires=1"
1992 .to_string(),
1993 storage_upload_request: http_request(
1994 "http://manager.internal/v1/storage/response?signature=DoNotCanonicalize%2FUpload",
1995 PresignedOperation::Put,
1996 ),
1997 },
1998 );
1999
2000 CommandServer::relativize_manager_urls(&mut envelope, "http://manager.internal/v1");
2001
2002 assert_eq!(
2003 envelope.response_handling.submit_response_url,
2004 "command/response?response_token=DoNotCanonicalize%2FValue&expires=1"
2005 );
2006 assert_eq!(
2007 envelope.response_handling.storage_upload_request.url(),
2008 "../storage/response?signature=DoNotCanonicalize%2FUpload"
2009 );
2010 let BodySpec::Storage {
2011 storage_get_request: Some(params),
2012 ..
2013 } = &envelope.params
2014 else {
2015 panic!("storage params request");
2016 };
2017 assert_eq!(params.url(), "../../storage/params?signature=params");
2018
2019 envelope.response_handling.storage_upload_request = http_request(
2020 "https://storage.example.com/result?signature=cloud",
2021 PresignedOperation::Put,
2022 );
2023 CommandServer::relativize_manager_urls(&mut envelope, "http://manager.internal/v1");
2024 assert_eq!(
2025 envelope.response_handling.storage_upload_request.url(),
2026 "https://storage.example.com/result?signature=cloud",
2027 "cloud-presigned URLs must remain byte-for-byte absolute"
2028 );
2029 }
2030}
2031
2032#[cfg(test)]
2033mod idempotency_key_tests {
2034 use super::*;
2035 use crate::server::{validate_command_name, validate_command_target_id};
2036
2037 #[test]
2038 fn definite_dispatch_rejection_is_classified_by_typed_error_data() {
2039 let rejected = AlienError::new(ErrorData::TransportDispatchRejected {
2040 message: "not accepted".to_string(),
2041 transport_type: Some("http".to_string()),
2042 target: Some("command-id".to_string()),
2043 });
2044 assert!(is_definite_dispatch_rejection(&rejected));
2045
2046 let ambiguous = AlienError::new(ErrorData::TransportDispatchFailed {
2047 message: "acknowledgement lost".to_string(),
2048 transport_type: Some("http".to_string()),
2049 target: Some("command-id".to_string()),
2050 });
2051 assert!(!is_definite_dispatch_rejection(&ambiguous));
2052 }
2053
2054 #[test]
2063 fn target_id_colon_guard_prevents_idempotency_key_collision() {
2064 let colliding = CommandServer::compose_idempotency_key("dep", "svc", "a:b", "k");
2065 assert_eq!(colliding, "dep:svc:a:b:k");
2066
2067 assert!(
2069 validate_command_target_id("svc:a").is_err(),
2070 "a ':'-bearing target id must be rejected so it cannot forge the rid segment"
2071 );
2072 assert!(validate_command_target_id("svc").is_ok());
2073 }
2074
2075 #[test]
2083 fn command_name_colon_guard_prevents_idempotency_key_collision() {
2084 let forged = CommandServer::compose_idempotency_key("dep", "svc", "a:b", "c");
2086 let legitimate = CommandServer::compose_idempotency_key("dep", "svc", "a", "b:c");
2087 assert_eq!(
2088 forged, legitimate,
2089 "these inputs are exactly the colliding pair the guard must separate"
2090 );
2091 assert_eq!(legitimate, "dep:svc:a:b:c");
2092
2093 let err = validate_command_name("a:b").expect_err("':'-bearing command must be rejected");
2098 assert_eq!(err.code, "INVALID_COMMAND");
2099 assert!(validate_command_name("a").is_ok());
2100 }
2101}