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
30type HmacSha256 = Hmac<Sha256>;
31
32const KV_VALUE_THRESHOLD: usize = 20_000;
35
36fn is_definite_dispatch_rejection(error: &crate::error::Error) -> bool {
37 matches!(
38 error.error.as_ref(),
39 Some(ErrorData::TransportDispatchRejected { .. })
40 )
41}
42
43pub mod axum_handlers;
44pub mod command_registry;
45pub mod storage;
46
47pub use crate::dispatchers::{CommandDispatcher, NullCommandDispatcher};
48pub use axum_handlers::{
49 create_axum_router, CommandPayloadResponse, HasCommandServer, StorePayloadRequest,
50};
51pub use command_registry::{
52 delivery_mode_for, select_command_target, validate_command_name, validate_command_target_id,
53 CommandAccessContext, CommandEnvelopeData, CommandMetadata, CommandRegistry, CommandStatus,
54 InMemoryCommandRegistry, ResolvedCommandTarget,
55};
56
57#[derive(Debug, Clone, Serialize, Deserialize)]
63struct CommandParamsData {
64 pub params: BodySpec,
65}
66
67#[derive(Debug, Clone, Serialize, Deserialize)]
69struct CommandResponseData {
70 pub response: CommandResponse,
71}
72
73#[derive(Debug, Clone, Serialize, Deserialize)]
75struct LeaseData {
76 pub lease_id: String,
77 pub acquired_at: DateTime<Utc>,
78 pub expires_at: DateTime<Utc>,
79 pub owner: String,
80 #[serde(default)]
83 pub completing: bool,
84}
85
86#[derive(Debug, Clone, PartialEq, Eq)]
88pub enum ExpectedLease {
89 Lease(String),
93 HeldLease(String),
96 NeverLeased,
98}
99
100#[derive(Debug, Clone, Serialize, Deserialize)]
102struct DeadlineIndexData {
103 pub command_id: String,
104 pub deadline: DateTime<Utc>,
105}
106
107pub struct CommandServer {
116 kv: Arc<dyn Kv>,
117 storage: Arc<dyn Storage>,
118 command_dispatcher: Arc<dyn CommandDispatcher>,
119 command_registry: Arc<dyn CommandRegistry>,
120 inline_max_bytes: usize,
121 base_url: String,
122 response_signing_key: Vec<u8>,
123 clock: Arc<dyn Fn() -> DateTime<Utc> + Send + Sync>,
124}
125
126impl CommandServer {
127 pub fn persists_operation_result_contract(&self) -> bool {
130 self.command_registry.persists_operation_result_contract()
131 }
132
133 pub fn new(
135 kv: Arc<dyn Kv>,
136 storage: Arc<dyn Storage>,
137 command_dispatcher: Arc<dyn CommandDispatcher>,
138 command_registry: Arc<dyn CommandRegistry>,
139 base_url: String,
140 response_signing_key: Vec<u8>,
141 ) -> Self {
142 Self {
143 kv,
144 storage,
145 command_dispatcher,
146 command_registry,
147 inline_max_bytes: INLINE_MAX_BYTES,
148 base_url,
149 response_signing_key,
150 clock: Arc::new(Utc::now),
151 }
152 }
153
154 pub fn with_inline_limit(
156 kv: Arc<dyn Kv>,
157 storage: Arc<dyn Storage>,
158 command_dispatcher: Arc<dyn CommandDispatcher>,
159 command_registry: Arc<dyn CommandRegistry>,
160 base_url: String,
161 inline_max_bytes: usize,
162 response_signing_key: Vec<u8>,
163 ) -> Self {
164 Self {
165 kv,
166 storage,
167 command_dispatcher,
168 command_registry,
169 inline_max_bytes,
170 base_url,
171 response_signing_key,
172 clock: Arc::new(Utc::now),
173 }
174 }
175
176 pub fn with_clock(mut self, clock: Arc<dyn Fn() -> DateTime<Utc> + Send + Sync>) -> Self {
178 self.clock = clock;
179 self
180 }
181
182 fn now(&self) -> DateTime<Utc> {
183 (self.clock)()
184 }
185
186 fn remaining_authority(&self, deadline: DateTime<Utc>) -> Result<Duration> {
187 let seconds = (deadline - self.now()).num_seconds() - 1;
190 if seconds <= 0 {
191 return Err(AlienError::new(ErrorData::CommandAuthorityExpired));
192 }
193 Ok(Duration::from_secs(seconds as u64))
194 }
195
196 fn check_storage_deadline(
197 &self,
198 request: &PresignedRequest,
199 deadline: DateTime<Utc>,
200 ) -> Result<()> {
201 if request.expiration > deadline || self.now() >= deadline {
202 return Err(AlienError::new(ErrorData::CommandAuthorityExpired));
203 }
204 Ok(())
205 }
206
207 const MAX_RESPONSE_TOKEN_LIFETIME_SECS: i64 = 7200;
209 const RESPONSE_CREDENTIAL_LIFETIME_SECS: u64 = 7200;
213
214 fn sign_response_url(
222 &self,
223 command_id: &str,
224 lease_id: Option<&str>,
225 deadline: DateTime<Utc>,
226 ) -> (String, i64) {
227 let expires = deadline.timestamp();
228 let token = self
229 .response_mac(command_id, lease_id, expires)
230 .finalize()
231 .into_bytes();
232 (hex::encode(token), expires)
233 }
234
235 fn response_mac(&self, command_id: &str, lease_id: Option<&str>, expires: i64) -> HmacSha256 {
236 let message = match lease_id {
237 Some(lease_id) => format!("commands.v2:{command_id}:{lease_id}:{expires}"),
238 None => format!("commands.v1:{command_id}:{expires}"),
239 };
240 let mut mac =
241 HmacSha256::new_from_slice(&self.response_signing_key).expect("HMAC accepts any key");
242 mac.update(message.as_bytes());
243 mac
244 }
245
246 pub fn verify_response_token(
253 &self,
254 command_id: &str,
255 lease_id: Option<&str>,
256 token: &str,
257 expires: i64,
258 ) -> bool {
259 if token.len() != 64 {
261 return false;
262 }
263
264 let mac = self.response_mac(command_id, lease_id, expires);
265
266 let Ok(token_bytes) = hex::decode(token) else {
268 return false;
269 };
270 let hmac_valid = mac.verify_slice(&token_bytes).is_ok();
271
272 let now = self.now().timestamp();
274 let not_expired = now < expires;
275 let within_max_lifetime = expires <= now + Self::MAX_RESPONSE_TOKEN_LIFETIME_SECS;
276
277 hmac_valid && not_expired && within_max_lifetime
278 }
279
280 pub async fn command_is_leased(&self, command_id: &str) -> Result<bool> {
283 let key = format!("cmd:{command_id}:lease");
284 Ok(self
285 .kv
286 .get(&key)
287 .await
288 .context(ErrorData::KvOperationFailed {
289 operation: "get".to_string(),
290 key,
291 message: "Failed to read the command lease".to_string(),
292 })?
293 .is_some())
294 }
295
296 async fn claim_lease_for_response(
316 &self,
317 command_id: &str,
318 expected: &ExpectedLease,
319 ) -> Result<()> {
320 const CLAIM_SECS: u64 = 60;
321 const ATTEMPTS: usize = 8;
322 let key = format!("cmd:{command_id}:lease");
323 let expected_id = match expected {
324 ExpectedLease::Lease(lease_id) | ExpectedLease::HeldLease(lease_id) => {
325 lease_id.as_str()
326 }
327 ExpectedLease::NeverLeased => "",
328 };
329 let superseded = || {
330 AlienError::new(ErrorData::LeaseSuperseded {
331 command_id: command_id.to_string(),
332 lease_id: expected_id.to_string(),
333 })
334 };
335 let kv_error = |operation: &str, message: &str| ErrorData::KvOperationFailed {
336 operation: operation.to_string(),
337 key: key.clone(),
338 message: message.to_string(),
339 };
340 let serialize = |lease: &LeaseData| {
341 serde_json::to_vec(lease)
342 .into_alien_error()
343 .context(ErrorData::SerializationFailed {
344 message: "Failed to serialize lease data".to_string(),
345 data_type: Some("LeaseData".to_string()),
346 })
347 };
348
349 for _ in 0..ATTEMPTS {
350 let entry = self
351 .kv
352 .get(&key)
353 .await
354 .context(kv_error("get", "Failed to read the command lease"))?;
355 match entry {
356 Some(entry) => {
357 let mut lease: LeaseData = serde_json::from_slice(&entry.value)
358 .into_alien_error()
359 .context(ErrorData::SerializationFailed {
360 message: "Failed to deserialize lease data".to_string(),
361 data_type: Some("LeaseData".to_string()),
362 })?;
363 let matches_expected = match expected {
367 ExpectedLease::Lease(id) | ExpectedLease::HeldLease(id) => {
368 *id == lease.lease_id
369 }
370 ExpectedLease::NeverLeased => lease.lease_id.is_empty() && lease.completing,
371 };
372 if !matches_expected {
373 return Err(superseded());
374 }
375 if lease.completing {
376 return Ok(());
377 }
378 lease.completing = true;
379 let remaining = (lease.expires_at - self.now()).num_seconds().max(1) as u64;
380 let claimed = self
381 .kv
382 .put(
383 &key,
384 serialize(&lease)?,
385 Some(PutOptions {
386 ttl: Some(Duration::from_secs(remaining)),
387 condition: PutCondition::Version(entry.version),
388 }),
389 )
390 .await
391 .context(kv_error("put", "Failed to claim the command lease"))?;
392 if claimed {
393 return Ok(());
394 }
395 }
396 None => {
397 if matches!(expected, ExpectedLease::HeldLease(_)) {
400 return Err(superseded());
401 }
402 let now = self.now();
403 let claim = LeaseData {
404 lease_id: expected_id.to_string(),
405 acquired_at: now,
406 expires_at: now + chrono::Duration::seconds(CLAIM_SECS as i64),
407 owner: "response".to_string(),
408 completing: true,
409 };
410 let claimed = self
411 .kv
412 .put(
413 &key,
414 serialize(&claim)?,
415 Some(PutOptions {
416 ttl: Some(Duration::from_secs(CLAIM_SECS)),
417 condition: PutCondition::Absent,
418 }),
419 )
420 .await
421 .context(kv_error("put", "Failed to claim the command lease"))?;
422 if claimed {
423 return Ok(());
424 }
425 }
426 }
427 }
428 Err(superseded())
429 }
430
431 pub async fn submit_command_response_for_lease(
435 &self,
436 command_id: &str,
437 response: CommandResponse,
438 expected: ExpectedLease,
439 ) -> Result<()> {
440 let expected = match expected {
442 ExpectedLease::Lease(id) | ExpectedLease::HeldLease(id) if id.is_empty() => {
443 ExpectedLease::NeverLeased
444 }
445 other => other,
446 };
447 self.claim_lease_for_response(command_id, &expected).await?;
448 self.submit_command_response(command_id, response).await?;
449 let _ = self.delete_lease(command_id).await;
452 Ok(())
453 }
454
455 pub async fn create_command(
467 &self,
468 request: CreateCommandRequest,
469 ) -> Result<CreateCommandResponse> {
470 self.validate_create_command(&request).await?;
472
473 let resolved_target = self
476 .command_registry
477 .resolve_target(
478 &request.deployment_id,
479 &request.command,
480 request.target_resource_id.as_deref(),
481 )
482 .await?;
483
484 let composed_idempotency_key = request.idempotency_key.as_ref().map(|idem_key| {
491 Self::compose_idempotency_key(
492 &request.deployment_id,
493 &resolved_target.target.resource_id,
494 &request.command,
495 idem_key,
496 )
497 });
498
499 if let Some(ref composed_key) = composed_idempotency_key {
501 if let Some(existing_id) = self.check_idempotency(composed_key).await? {
502 let status = self
504 .command_registry
505 .get_command_status(&existing_id)
506 .await?;
507 if let Some(s) = status {
508 return Ok(CreateCommandResponse {
509 command_id: existing_id,
510 created: false,
511 state: s.state,
512 storage_upload: None,
513 inline_allowed_up_to: self.inline_max_bytes as u64,
514 next: "poll".to_string(),
515 });
516 }
517 }
518 }
519
520 let (initial_state, request_size_bytes) = match &request.params {
522 BodySpec::Inline { inline_base64 } => {
523 let size = inline_base64.len() as u64;
524 (CommandState::Pending, Some(size))
525 }
526 BodySpec::Storage { size, .. } => {
527 if size.unwrap_or(0) > self.inline_max_bytes as u64 {
528 (CommandState::PendingUpload, *size)
529 } else {
530 (CommandState::Pending, *size)
531 }
532 }
533 };
534
535 let metadata = self
537 .command_registry
538 .create_command(
539 &request.deployment_id,
540 &request.command,
541 &resolved_target,
542 initial_state,
543 request.deadline,
544 request_size_bytes,
545 request.operation_result_contract.clone(),
546 )
547 .await?;
548
549 let command_id = metadata.command_id;
550 let delivery_mode = metadata.delivery_mode;
551
552 if let Some(ref composed_key) = composed_idempotency_key {
559 if let Some(winner_id) = self.store_idempotency(composed_key, &command_id).await? {
560 let _ = self
561 .command_registry
562 .complete_command(
563 &command_id,
564 CommandState::Failed,
565 self.now(),
566 None,
567 Some(serde_json::json!({
568 "code": "IDEMPOTENT_DUPLICATE",
569 "message": format!(
570 "Superseded by concurrent create '{}' with the same idempotency key",
571 winner_id
572 ),
573 })),
574 )
575 .await?;
576 let status = self.command_registry.get_command_status(&winner_id).await?;
577 let state = status.map(|s| s.state).unwrap_or(CommandState::Pending);
578 return Ok(CreateCommandResponse {
579 command_id: winner_id,
580 created: false,
581 state,
582 storage_upload: None,
583 inline_allowed_up_to: self.inline_max_bytes as u64,
584 next: "poll".to_string(),
585 });
586 }
587 }
588
589 self.store_params(&command_id, &request.params).await?;
591
592 let storage_upload = if initial_state == CommandState::PendingUpload {
594 Some(self.generate_params_upload(&command_id).await?)
595 } else {
596 None
597 };
598
599 let (final_state, next_action) = if initial_state == CommandState::Pending {
601 match delivery_mode {
602 CommandDeliveryMode::Push => {
603 let state = self
605 .dispatch_command_push(&command_id, &request.deployment_id)
606 .await?;
607 (state, "poll")
608 }
609 CommandDeliveryMode::Pull => {
610 self.create_pending_index(
613 &request.deployment_id,
614 &metadata.target.resource_id,
615 &command_id,
616 )
617 .await?;
618 debug!("Command {} ready for target-scoped lease", command_id);
619 (CommandState::Pending, "poll")
620 }
621 }
622 } else {
623 (initial_state, "upload")
625 };
626
627 if let Some(deadline) = request.deadline {
629 self.create_deadline_index(&command_id, deadline).await?;
630 }
631
632 Ok(CreateCommandResponse {
633 command_id,
634 created: true,
635 state: final_state,
636 storage_upload,
637 inline_allowed_up_to: self.inline_max_bytes as u64,
638 next: next_action.to_string(),
639 })
640 }
641
642 pub async fn upload_complete(
644 &self,
645 command_id: &str,
646 upload_request: UploadCompleteRequest,
647 ) -> Result<UploadCompleteResponse> {
648 let status = self
650 .command_registry
651 .get_command_status(command_id)
652 .await?
653 .ok_or_else(|| {
654 AlienError::new(ErrorData::CommandNotFound {
655 command_id: command_id.to_string(),
656 })
657 })?;
658
659 if status.state != CommandState::PendingUpload {
661 return Err(AlienError::new(ErrorData::InvalidStateTransition {
662 from: status.state.as_ref().to_string(),
663 to: CommandState::Pending.as_ref().to_string(),
664 }));
665 }
666
667 let storage_get_request = self.generate_storage_get_request(command_id).await?;
669 let params = BodySpec::Storage {
670 size: Some(upload_request.size),
671 storage_get_request: Some(storage_get_request),
672 storage_put_used: None,
673 };
674 self.store_params(command_id, ¶ms).await?;
675
676 let transitioned = self
678 .command_registry
679 .update_command_state(command_id, CommandState::Pending, None, None, None, None)
680 .await?;
681 if !transitioned {
682 let current_state = self
683 .command_registry
684 .get_command_status(command_id)
685 .await?
686 .map(|current| current.state)
687 .unwrap_or(status.state);
688 return Err(AlienError::new(ErrorData::InvalidStateTransition {
689 from: current_state.as_ref().to_string(),
690 to: CommandState::Pending.as_ref().to_string(),
691 }));
692 }
693
694 let metadata = self
696 .command_registry
697 .get_command_metadata(command_id)
698 .await?
699 .ok_or_else(|| {
700 AlienError::new(ErrorData::CommandNotFound {
701 command_id: command_id.to_string(),
702 })
703 })?;
704
705 let final_state = match metadata.delivery_mode {
706 CommandDeliveryMode::Push => {
707 self.dispatch_command_push(command_id, &status.deployment_id)
708 .await?
709 }
710 CommandDeliveryMode::Pull => {
711 self.create_pending_index(
712 &status.deployment_id,
713 &metadata.target.resource_id,
714 command_id,
715 )
716 .await?;
717 debug!(
718 "Command {} ready for pull after upload (target will poll)",
719 command_id
720 );
721 CommandState::Pending
722 }
723 };
724
725 Ok(UploadCompleteResponse {
726 command_id: command_id.to_string(),
727 state: final_state,
728 })
729 }
730
731 pub async fn get_command_status(&self, command_id: &str) -> Result<CommandStatusResponse> {
735 let status = self
737 .command_registry
738 .get_command_status(command_id)
739 .await?
740 .ok_or_else(|| {
741 AlienError::new(ErrorData::CommandNotFound {
742 command_id: command_id.to_string(),
743 })
744 })?;
745
746 if let Some(deadline) = status.deadline {
748 if self.now() > deadline && !status.state.is_terminal() {
749 let won = self
754 .command_registry
755 .complete_command(command_id, CommandState::Expired, self.now(), None, None)
756 .await?;
757 if won {
758 self.delete_pending_index(
760 &status.deployment_id,
761 &status.target.resource_id,
762 command_id,
763 )
764 .await?;
765
766 return Ok(CommandStatusResponse {
768 command_id: command_id.to_string(),
769 state: CommandState::Expired,
770 attempt: status.attempt,
771 target: status.target,
772 response: None,
773 });
774 }
775 let status = self
778 .command_registry
779 .get_command_status(command_id)
780 .await?
781 .ok_or_else(|| {
782 AlienError::new(ErrorData::CommandNotFound {
783 command_id: command_id.to_string(),
784 })
785 })?;
786 let response = if status.state.is_terminal() {
787 self.get_response(command_id).await?
788 } else {
789 None
790 };
791 return Ok(CommandStatusResponse {
792 command_id: command_id.to_string(),
793 state: status.state,
794 attempt: status.attempt,
795 target: status.target,
796 response,
797 });
798 }
799 }
800
801 let response = if status.state.is_terminal() {
803 self.get_response(command_id).await?
804 } else {
805 None
806 };
807
808 Ok(CommandStatusResponse {
809 command_id: command_id.to_string(),
810 state: status.state,
811 attempt: status.attempt,
812 target: status.target,
813 response,
814 })
815 }
816
817 pub async fn submit_command_response(
821 &self,
822 command_id: &str,
823 mut response: CommandResponse,
824 ) -> Result<()> {
825 let status = self
827 .command_registry
828 .get_command_status(command_id)
829 .await?
830 .ok_or_else(|| {
831 AlienError::new(ErrorData::CommandNotFound {
832 command_id: command_id.to_string(),
833 })
834 })?;
835
836 if status.state.is_terminal() {
838 debug!(
839 "Ignoring duplicate response for terminal command {}",
840 command_id
841 );
842 return Ok(());
843 }
844
845 if status.state != CommandState::Dispatched {
847 return Err(AlienError::new(ErrorData::InvalidStateTransition {
848 from: status.state.as_ref().to_string(),
849 to: CommandState::Succeeded.as_ref().to_string(),
850 }));
851 }
852
853 if let CommandResponse::Success {
855 response: ref mut body,
856 } = response
857 {
858 if let BodySpec::Storage {
859 size,
860 storage_get_request,
861 storage_put_used,
862 } = body
863 {
864 if storage_get_request.is_none() && storage_put_used.unwrap_or(false) {
865 let get_request = self
866 .generate_response_storage_get_request(command_id)
867 .await?;
868 *body = BodySpec::Storage {
869 size: *size,
870 storage_get_request: Some(get_request),
871 storage_put_used: *storage_put_used,
872 };
873 }
874 }
875 }
876
877 self.store_response(command_id, &response).await?;
879
880 let (new_state, error) = if response.is_success() {
889 (CommandState::Succeeded, None)
890 } else if let CommandResponse::Error { code, message, .. } = &response {
891 (
892 CommandState::Failed,
893 Some(serde_json::json!({ "code": code, "message": message })),
894 )
895 } else {
896 (CommandState::Failed, None)
897 };
898
899 let response_size = match &response {
900 CommandResponse::Success {
901 response: BodySpec::Inline { inline_base64 },
902 } => Some(inline_base64.len() as u64),
903 CommandResponse::Success {
904 response: BodySpec::Storage { size, .. },
905 } => *size,
906 _ => None,
907 };
908
909 let won = self
919 .command_registry
920 .complete_command(command_id, new_state, self.now(), response_size, error)
921 .await?;
922 if !won {
923 debug!(
924 "Ignoring duplicate response for command {} (lost the terminal transition race)",
925 command_id
926 );
927 return Ok(());
928 }
929 self.store_response(command_id, &response).await?;
930
931 if let Err(e) = self.delete_lease(command_id).await {
936 warn!(
937 command_id,
938 error = %e,
939 "Failed to clean up lease after terminal response; will be reaped on next lease scan"
940 );
941 }
942
943 if let Err(e) = self
946 .delete_pending_index(
947 &status.deployment_id,
948 &status.target.resource_id,
949 command_id,
950 )
951 .await
952 {
953 warn!(
954 command_id,
955 error = %e,
956 "Failed to clean up pending index after terminal response; will be reaped on next lease scan"
957 );
958 }
959
960 info!(
961 "Command {} completed with state {:?}",
962 command_id, new_state
963 );
964 Ok(())
965 }
966
967 pub async fn acquire_lease(
971 &self,
972 deployment_id: &str,
973 lease_request: &LeaseRequest,
974 ) -> Result<LeaseResponse> {
975 self.acquire_lease_with_deadline(deployment_id, lease_request, None)
976 .await
977 }
978
979 pub async fn acquire_lease_with_deadline(
982 &self,
983 deployment_id: &str,
984 lease_request: &LeaseRequest,
985 authority_deadline: Option<DateTime<Utc>>,
986 ) -> Result<LeaseResponse> {
987 if let Some(deadline) = authority_deadline {
988 self.remaining_authority(deadline)?;
989 }
990 let mut leases = Vec::new();
991
992 let target_prefix = format!(
995 "target:{}:{}:pending:",
996 deployment_id, lease_request.target.resource_id
997 );
998 let scan_result = self
999 .kv
1000 .scan_prefix(&target_prefix, Some(lease_request.max_leases * 2), None)
1001 .await
1002 .into_alien_error()
1003 .context(ErrorData::KvOperationFailed {
1004 operation: "scan_prefix".to_string(),
1005 key: target_prefix.clone(),
1006 message: "Failed to scan for pending commands".to_string(),
1007 })?;
1008
1009 for entry in scan_result.items {
1010 let index_key = entry.key;
1011 if leases.len() >= lease_request.max_leases {
1012 break;
1013 }
1014
1015 let command_id = self.extract_command_id_from_index_key(&index_key)?;
1016
1017 let lease_id = format!("lease_{}", Uuid::new_v4());
1019 let lease_duration = Duration::from_secs(lease_request.lease_seconds);
1020 let expires_at =
1021 Utc::now() + chrono::Duration::seconds(lease_request.lease_seconds as i64);
1022
1023 let lease_data = LeaseData {
1024 lease_id: lease_id.clone(),
1025 acquired_at: Utc::now(),
1026 expires_at,
1027 owner: deployment_id.to_string(),
1028 completing: false,
1029 };
1030
1031 let lease_key = format!("cmd:{}:lease", command_id);
1032 let lease_value = serde_json::to_vec(&lease_data).into_alien_error().context(
1033 ErrorData::SerializationFailed {
1034 message: "Failed to serialize lease data".to_string(),
1035 data_type: Some("LeaseData".to_string()),
1036 },
1037 )?;
1038
1039 let options = Some(PutOptions {
1040 ttl: Some(lease_duration),
1041 condition: PutCondition::Absent,
1042 });
1043
1044 let success = self
1045 .kv
1046 .put(&lease_key, lease_value, options)
1047 .await
1048 .context(ErrorData::KvOperationFailed {
1049 operation: "put".to_string(),
1050 key: lease_key.clone(),
1051 message: "Failed to create lease".to_string(),
1052 })?;
1053
1054 if !success {
1055 continue;
1057 }
1058
1059 let reverse_key = format!("lease:{}", lease_id);
1064 self.kv
1065 .put(
1066 &reverse_key,
1067 command_id.as_bytes().to_vec(),
1068 Some(PutOptions {
1069 ttl: Some(lease_duration),
1070 condition: PutCondition::None,
1071 }),
1072 )
1073 .await
1074 .context(ErrorData::KvOperationFailed {
1075 operation: "put".to_string(),
1076 key: reverse_key,
1077 message: "Failed to create lease reverse index".to_string(),
1078 })?;
1079
1080 let mut metadata = match self
1082 .command_registry
1083 .get_command_metadata(&command_id)
1084 .await?
1085 {
1086 Some(m) => m,
1087 None => {
1088 self.delete_lease(&command_id).await?;
1090 let _ = self.kv.delete(&index_key, None).await;
1091 continue;
1092 }
1093 };
1094
1095 if metadata.state == CommandState::Dispatched {
1103 self.command_registry.increment_attempt(&command_id).await?;
1104 metadata.attempt += 1;
1105 }
1106
1107 if metadata.target != lease_request.target {
1115 self.delete_lease(&command_id).await?;
1116 return Err(AlienError::new(ErrorData::Other {
1117 message: format!(
1118 "Pending index corruption: command '{}' is indexed under target '{}' \
1119 but the registry says it belongs to target '{}' — refusing to deliver",
1120 command_id, lease_request.target.resource_id, metadata.target.resource_id,
1121 ),
1122 }));
1123 }
1124
1125 if metadata.state.is_terminal() {
1127 self.delete_lease(&command_id).await?;
1129 let _ = self.kv.delete(&index_key, None).await;
1130 continue;
1131 }
1132
1133 if let Some(deadline) = metadata.deadline {
1136 if Utc::now() > deadline {
1137 let _ = self
1138 .command_registry
1139 .complete_command(
1140 &command_id,
1141 CommandState::Expired,
1142 Utc::now(),
1143 None,
1144 None,
1145 )
1146 .await?;
1147 self.delete_lease(&command_id).await?;
1148 let _ = self.kv.delete(&index_key, None).await;
1149 continue;
1150 }
1151 }
1152
1153 let params = match self.get_params(&command_id).await? {
1155 Some(p) => p,
1156 None => {
1157 self.delete_lease(&command_id).await?;
1159 continue;
1160 }
1161 };
1162
1163 let dispatched = self
1168 .command_registry
1169 .mark_dispatched_if_not_terminal(&command_id, Utc::now())
1170 .await?;
1171 if !dispatched {
1172 debug!(
1173 command_id = %command_id,
1174 "Command turned terminal while leasing; releasing the lease"
1175 );
1176 self.delete_lease(&command_id).await?;
1177 let _ = self.kv.delete(&index_key, None).await;
1178 continue;
1179 }
1180
1181 let response_deadline = authority_deadline.map(|_| expires_at);
1195 let mut envelope = self
1196 .build_envelope(
1197 &command_id,
1198 &metadata,
1199 params,
1200 authority_deadline,
1201 response_deadline,
1202 Some(&lease_id),
1203 )
1204 .await?;
1205 Self::relativize_manager_urls(&mut envelope, &self.base_url);
1206
1207 leases.push(LeaseInfo {
1208 lease_id,
1209 lease_expires_at: expires_at,
1210 command_id: command_id.clone(),
1211 attempt: metadata.attempt,
1212 envelope,
1213 });
1214 }
1215
1216 Ok(LeaseResponse { leases })
1217 }
1218
1219 fn relativize_manager_urls(envelope: &mut Envelope, base_url: &str) {
1224 let Ok(mut lease_endpoint) = reqwest::Url::parse(base_url) else {
1225 return;
1228 };
1229 let Ok(mut segments) = lease_endpoint.path_segments_mut() else {
1230 return;
1231 };
1232 segments.pop_if_empty().push("commands").push("leases");
1233 drop(segments);
1234 lease_endpoint.set_query(None);
1235 lease_endpoint.set_fragment(None);
1236
1237 let relativize = |target: &mut String| {
1238 let Ok(mut target_url) = reqwest::Url::parse(target.as_str()) else {
1239 return;
1240 };
1241 let suffix = target
1242 .find(['?', '#'])
1243 .map(|index| target[index..].to_string())
1244 .unwrap_or_default();
1245 target_url.set_query(None);
1246 target_url.set_fragment(None);
1247 if let Some(relative) = lease_endpoint.make_relative(&target_url) {
1248 *target = format!("{relative}{suffix}");
1249 }
1250 };
1251
1252 relativize(&mut envelope.response_handling.submit_response_url);
1253 if let alien_core::presigned::PresignedRequestBackend::Http { url, .. } =
1254 &mut envelope.response_handling.storage_upload_request.backend
1255 {
1256 relativize(url);
1257 }
1258 if let BodySpec::Storage {
1259 storage_get_request: Some(request),
1260 ..
1261 } = &mut envelope.params
1262 {
1263 if let alien_core::presigned::PresignedRequestBackend::Http { url, .. } =
1264 &mut request.backend
1265 {
1266 relativize(url);
1267 }
1268 }
1269 }
1270
1271 pub async fn release_lease(&self, command_id: &str, lease_id: &str) -> Result<()> {
1275 let lease_key = format!("cmd:{}:lease", command_id);
1276
1277 if let Ok(Some(lease_data)) = self.kv.get(&lease_key).await {
1279 let lease: LeaseData = serde_json::from_slice(&lease_data.value)
1280 .into_alien_error()
1281 .context(ErrorData::SerializationFailed {
1282 message: "Failed to deserialize lease data".to_string(),
1283 data_type: Some("LeaseData".to_string()),
1284 })?;
1285
1286 if lease.lease_id != lease_id {
1287 return Err(AlienError::new(ErrorData::LeaseNotFound {
1288 lease_id: lease_id.to_string(),
1289 }));
1290 }
1291
1292 self.delete_lease(command_id).await?;
1294 let _ = self.kv.delete(&format!("lease:{}", lease_id), None).await;
1295
1296 let released = self
1299 .command_registry
1300 .update_command_state(command_id, CommandState::Pending, None, None, None, None)
1301 .await?;
1302 if released {
1303 self.command_registry.increment_attempt(command_id).await?;
1306 }
1307
1308 debug!(
1310 released,
1311 "Lease {} released for command {}", lease_id, command_id
1312 );
1313 }
1314
1315 Ok(())
1316 }
1317
1318 pub async fn get_command_deployment_id(&self, command_id: &str) -> Result<Option<String>> {
1323 let status = self.command_registry.get_command_status(command_id).await?;
1324 Ok(status.map(|s| s.deployment_id))
1325 }
1326
1327 pub async fn get_command_status_record(
1329 &self,
1330 command_id: &str,
1331 ) -> Result<Option<CommandStatus>> {
1332 self.command_registry.get_command_status(command_id).await
1333 }
1334
1335 pub async fn get_command_access_context(
1337 &self,
1338 command_id: &str,
1339 ) -> Result<Option<CommandAccessContext>> {
1340 self.command_registry
1341 .get_command_access_context(command_id)
1342 .await
1343 }
1344
1345 pub async fn get_lease_owner(&self, lease_id: &str) -> Result<Option<(String, String)>> {
1353 let reverse_key = format!("lease:{}", lease_id);
1354 let Some(command_id_bytes) =
1355 self.kv
1356 .get(&reverse_key)
1357 .await
1358 .context(ErrorData::KvOperationFailed {
1359 operation: "get".to_string(),
1360 key: reverse_key.clone(),
1361 message: "Failed to look up lease reverse index".to_string(),
1362 })?
1363 else {
1364 return Ok(None);
1365 };
1366 let command_id = String::from_utf8(command_id_bytes.value).map_err(|_| {
1367 AlienError::new(ErrorData::Other {
1368 message: format!("Lease reverse index '{}' is not valid UTF-8", reverse_key),
1369 })
1370 })?;
1371
1372 let lease_key = format!("cmd:{}:lease", command_id);
1373 let Some(lease_data) =
1374 self.kv
1375 .get(&lease_key)
1376 .await
1377 .context(ErrorData::KvOperationFailed {
1378 operation: "get".to_string(),
1379 key: lease_key,
1380 message: "Failed to look up lease".to_string(),
1381 })?
1382 else {
1383 return Ok(None);
1384 };
1385 let lease: LeaseData = serde_json::from_slice(&lease_data.value)
1386 .into_alien_error()
1387 .context(ErrorData::SerializationFailed {
1388 message: "Failed to deserialize lease data".to_string(),
1389 data_type: Some("LeaseData".to_string()),
1390 })?;
1391 if lease.lease_id != lease_id {
1392 return Ok(None);
1393 }
1394
1395 Ok(Some((command_id, lease.owner)))
1396 }
1397
1398 pub async fn release_lease_by_id(&self, lease_id: &str) -> Result<()> {
1400 match self.get_lease_owner(lease_id).await? {
1401 Some((command_id, _owner)) => self.release_lease(&command_id, lease_id).await,
1402 None => Err(AlienError::new(ErrorData::LeaseNotFound {
1403 lease_id: lease_id.to_string(),
1404 })),
1405 }
1406 }
1407
1408 async fn validate_create_command(&self, request: &CreateCommandRequest) -> Result<()> {
1413 validate_operation_result_contract_request(
1414 &request.command,
1415 request.operation_result_contract.is_some(),
1416 self.command_registry.persists_operation_result_contract(),
1417 )?;
1418
1419 if request.command.is_empty() {
1420 return Err(AlienError::new(ErrorData::InvalidCommand {
1421 message: "Command name cannot be empty".to_string(),
1422 }));
1423 }
1424
1425 validate_command_name(&request.command)?;
1433
1434 if request.deployment_id.is_empty() {
1435 return Err(AlienError::new(ErrorData::InvalidCommand {
1436 message: "Deployment ID cannot be empty".to_string(),
1437 }));
1438 }
1439
1440 if let Some(deadline) = request.deadline {
1441 if deadline <= self.now() {
1442 return Err(AlienError::new(ErrorData::InvalidCommand {
1443 message: "Deadline must be in the future".to_string(),
1444 }));
1445 }
1446 }
1447
1448 Ok(())
1449 }
1450
1451 fn compose_idempotency_key(
1459 deployment_id: &str,
1460 target_resource_id: &str,
1461 command_name: &str,
1462 idem_key: &str,
1463 ) -> String {
1464 debug_assert!(
1474 !target_resource_id.contains(':'),
1475 "target_resource_id must be ':'-free before key composition: {target_resource_id}"
1476 );
1477 format!(
1478 "{}:{}:{}:{}",
1479 deployment_id, target_resource_id, command_name, idem_key
1480 )
1481 }
1482
1483 fn storage_idempotency_key(composed_key: &str) -> String {
1487 let legacy_key = format!("idem:{composed_key}");
1488 if validate_key(&legacy_key).is_ok() {
1489 legacy_key
1490 } else {
1491 format!(
1492 "idem2:{}",
1493 hex::encode(Sha256::digest(composed_key.as_bytes()))
1494 )
1495 }
1496 }
1497
1498 async fn check_idempotency(&self, idem_key: &str) -> Result<Option<String>> {
1499 let key = Self::storage_idempotency_key(idem_key);
1500 if let Some(data) = self
1501 .kv
1502 .get(&key)
1503 .await
1504 .context(ErrorData::KvOperationFailed {
1505 operation: "get".to_string(),
1506 key: key.clone(),
1507 message: "Failed to check idempotency".to_string(),
1508 })?
1509 {
1510 let command_id = String::from_utf8(data.value).into_alien_error().context(
1511 ErrorData::SerializationFailed {
1512 message: "Invalid idempotency data".to_string(),
1513 data_type: Some("String".to_string()),
1514 },
1515 )?;
1516 return Ok(Some(command_id));
1517 }
1518 Ok(None)
1519 }
1520
1521 async fn store_idempotency(&self, idem_key: &str, command_id: &str) -> Result<Option<String>> {
1529 let key = Self::storage_idempotency_key(idem_key);
1530 let ttl = Duration::from_secs(24 * 60 * 60); let won = self
1532 .kv
1533 .put(
1534 &key,
1535 command_id.as_bytes().to_vec(),
1536 Some(PutOptions {
1537 ttl: Some(ttl),
1538 condition: PutCondition::Absent,
1539 }),
1540 )
1541 .await
1542 .context(ErrorData::KvOperationFailed {
1543 operation: "put".to_string(),
1544 key: key.clone(),
1545 message: "Failed to store idempotency".to_string(),
1546 })?;
1547 if won {
1548 return Ok(None);
1549 }
1550 match self.check_idempotency(idem_key).await? {
1554 Some(winner_id) => Ok(Some(winner_id)),
1555 None => Err(AlienError::new(ErrorData::Other {
1556 message: format!(
1557 "Idempotency key '{}' was concurrently claimed but has no winner entry",
1558 key
1559 ),
1560 })),
1561 }
1562 }
1563
1564 pub async fn store_params(&self, command_id: &str, params: &BodySpec) -> Result<()> {
1567 let key = format!("cmd:{}:params", command_id);
1568
1569 let data = CommandParamsData {
1571 params: params.clone(),
1572 };
1573 let value = serde_json::to_vec(&data).into_alien_error().context(
1574 ErrorData::SerializationFailed {
1575 message: "Failed to serialize params".to_string(),
1576 data_type: Some("CommandParamsData".to_string()),
1577 },
1578 )?;
1579
1580 if value.len() <= KV_VALUE_THRESHOLD {
1582 self.kv
1583 .put(&key, value, None)
1584 .await
1585 .context(ErrorData::KvOperationFailed {
1586 operation: "put".to_string(),
1587 key: key.clone(),
1588 message: "Failed to store params".to_string(),
1589 })?;
1590 return Ok(());
1591 }
1592
1593 if let BodySpec::Inline { inline_base64 } = params {
1595 let raw_bytes = general_purpose::STANDARD
1596 .decode(inline_base64)
1597 .into_alien_error()
1598 .context(ErrorData::SerializationFailed {
1599 message: "Failed to decode inline base64 params for auto-promotion".to_string(),
1600 data_type: Some("base64".to_string()),
1601 })?;
1602
1603 let raw_len = raw_bytes.len() as u64;
1604 let blob_path = StoragePath::from(format!("arc/commands/{}/params", command_id));
1605
1606 self.storage
1607 .put(&blob_path, Bytes::from(raw_bytes).into())
1608 .await
1609 .into_alien_error()
1610 .context(ErrorData::StorageOperationFailed {
1611 message: "Failed to auto-promote params to blob storage".to_string(),
1612 operation: Some("put".to_string()),
1613 path: Some(blob_path.to_string()),
1614 })?;
1615
1616 debug!(
1617 "Auto-promoted params for command {} to blob ({} bytes raw)",
1618 command_id, raw_len
1619 );
1620
1621 let promoted = CommandParamsData {
1623 params: BodySpec::Storage {
1624 size: Some(raw_len),
1625 storage_get_request: None,
1626 storage_put_used: Some(true),
1627 },
1628 };
1629 let promoted_value = serde_json::to_vec(&promoted).into_alien_error().context(
1630 ErrorData::SerializationFailed {
1631 message: "Failed to serialize promoted params reference".to_string(),
1632 data_type: Some("CommandParamsData".to_string()),
1633 },
1634 )?;
1635 self.kv.put(&key, promoted_value, None).await.context(
1636 ErrorData::KvOperationFailed {
1637 operation: "put".to_string(),
1638 key: key.clone(),
1639 message: "Failed to store promoted params reference".to_string(),
1640 },
1641 )?;
1642 return Ok(());
1643 }
1644
1645 self.kv
1647 .put(&key, value, None)
1648 .await
1649 .context(ErrorData::KvOperationFailed {
1650 operation: "put".to_string(),
1651 key: key.clone(),
1652 message: "Failed to store params".to_string(),
1653 })?;
1654 Ok(())
1655 }
1656
1657 pub async fn get_params(&self, command_id: &str) -> Result<Option<BodySpec>> {
1658 let key = format!("cmd:{}:params", command_id);
1659 if let Some(value) = self
1660 .kv
1661 .get(&key)
1662 .await
1663 .context(ErrorData::KvOperationFailed {
1664 operation: "get".to_string(),
1665 key: key.clone(),
1666 message: "Failed to get params".to_string(),
1667 })?
1668 {
1669 let data: CommandParamsData = serde_json::from_slice(&value.value)
1670 .into_alien_error()
1671 .context(ErrorData::SerializationFailed {
1672 message: "Failed to deserialize params".to_string(),
1673 data_type: Some("CommandParamsData".to_string()),
1674 })?;
1675 return Ok(Some(data.params));
1676 }
1677 Ok(None)
1678 }
1679
1680 pub async fn store_response(&self, command_id: &str, response: &CommandResponse) -> Result<()> {
1683 let key = format!("cmd:{}:response", command_id);
1684 let data = CommandResponseData {
1685 response: response.clone(),
1686 };
1687 let value = serde_json::to_vec(&data).into_alien_error().context(
1688 ErrorData::SerializationFailed {
1689 message: "Failed to serialize response".to_string(),
1690 data_type: Some("CommandResponseData".to_string()),
1691 },
1692 )?;
1693
1694 if value.len() <= KV_VALUE_THRESHOLD {
1696 self.kv
1697 .put(&key, value, None)
1698 .await
1699 .context(ErrorData::KvOperationFailed {
1700 operation: "put".to_string(),
1701 key: key.clone(),
1702 message: "Failed to store response".to_string(),
1703 })?;
1704 return Ok(());
1705 }
1706
1707 if let CommandResponse::Success {
1709 response: BodySpec::Inline { inline_base64 },
1710 } = response
1711 {
1712 let raw_bytes = general_purpose::STANDARD
1713 .decode(inline_base64)
1714 .into_alien_error()
1715 .context(ErrorData::SerializationFailed {
1716 message: "Failed to decode inline base64 response for auto-promotion"
1717 .to_string(),
1718 data_type: Some("base64".to_string()),
1719 })?;
1720
1721 let raw_len = raw_bytes.len() as u64;
1722 let blob_path = StoragePath::from(format!("arc/commands/{}/response", command_id));
1723
1724 self.storage
1725 .put(&blob_path, Bytes::from(raw_bytes).into())
1726 .await
1727 .into_alien_error()
1728 .context(ErrorData::StorageOperationFailed {
1729 message: "Failed to auto-promote response to blob storage".to_string(),
1730 operation: Some("put".to_string()),
1731 path: Some(blob_path.to_string()),
1732 })?;
1733
1734 let get_request = self
1736 .generate_response_storage_get_request(command_id)
1737 .await?;
1738
1739 debug!(
1740 "Auto-promoted response for command {} to blob ({} bytes raw)",
1741 command_id, raw_len
1742 );
1743
1744 let promoted = CommandResponseData {
1746 response: CommandResponse::Success {
1747 response: BodySpec::Storage {
1748 size: Some(raw_len),
1749 storage_get_request: Some(get_request),
1750 storage_put_used: Some(true),
1751 },
1752 },
1753 };
1754 let promoted_value = serde_json::to_vec(&promoted).into_alien_error().context(
1755 ErrorData::SerializationFailed {
1756 message: "Failed to serialize promoted response reference".to_string(),
1757 data_type: Some("CommandResponseData".to_string()),
1758 },
1759 )?;
1760 self.kv.put(&key, promoted_value, None).await.context(
1761 ErrorData::KvOperationFailed {
1762 operation: "put".to_string(),
1763 key: key.clone(),
1764 message: "Failed to store promoted response reference".to_string(),
1765 },
1766 )?;
1767 return Ok(());
1768 }
1769
1770 self.kv
1772 .put(&key, value, None)
1773 .await
1774 .context(ErrorData::KvOperationFailed {
1775 operation: "put".to_string(),
1776 key: key.clone(),
1777 message: "Failed to store response".to_string(),
1778 })?;
1779 Ok(())
1780 }
1781
1782 pub async fn get_response(&self, command_id: &str) -> Result<Option<CommandResponse>> {
1783 let key = format!("cmd:{}:response", command_id);
1784 if let Some(value) = self
1785 .kv
1786 .get(&key)
1787 .await
1788 .context(ErrorData::KvOperationFailed {
1789 operation: "get".to_string(),
1790 key: key.clone(),
1791 message: "Failed to get response".to_string(),
1792 })?
1793 {
1794 let data: CommandResponseData = serde_json::from_slice(&value.value)
1795 .into_alien_error()
1796 .context(ErrorData::SerializationFailed {
1797 message: "Failed to deserialize response".to_string(),
1798 data_type: Some("CommandResponseData".to_string()),
1799 })?;
1800 return Ok(Some(data.response));
1801 }
1802 Ok(None)
1803 }
1804
1805 async fn create_pending_index(
1808 &self,
1809 deployment_id: &str,
1810 target_resource_id: &str,
1811 command_id: &str,
1812 ) -> Result<()> {
1813 debug_assert!(
1817 !target_resource_id.contains(':'),
1818 "target_resource_id must be ':'-free in the pending index: {target_resource_id}"
1819 );
1820 let timestamp = self.now().timestamp_nanos_opt().unwrap_or(0);
1821 let key = format!(
1822 "target:{}:{}:pending:{}:{}",
1823 deployment_id, target_resource_id, timestamp, command_id
1824 );
1825
1826 self.kv
1828 .put(&key, vec![], None)
1829 .await
1830 .context(ErrorData::KvOperationFailed {
1831 operation: "put".to_string(),
1832 key: key.clone(),
1833 message: "Failed to create pending index".to_string(),
1834 })?;
1835 Ok(())
1836 }
1837
1838 async fn delete_pending_index(
1839 &self,
1840 deployment_id: &str,
1841 target_resource_id: &str,
1842 command_id: &str,
1843 ) -> Result<()> {
1844 let prefix = format!("target:{}:{}:pending:", deployment_id, target_resource_id);
1846 let scan_result = self
1847 .kv
1848 .scan_prefix(&prefix, Some(100), None)
1849 .await
1850 .into_alien_error()
1851 .context(ErrorData::KvOperationFailed {
1852 operation: "scan_prefix".to_string(),
1853 key: prefix.clone(),
1854 message: "Failed to scan pending index".to_string(),
1855 })?;
1856
1857 for entry in scan_result.items {
1858 if entry.key.ends_with(&format!(":{}", command_id)) {
1859 let _ = self.kv.delete(&entry.key, None).await;
1860 break;
1861 }
1862 }
1863 Ok(())
1864 }
1865
1866 async fn delete_lease(&self, command_id: &str) -> Result<()> {
1869 let key = format!("cmd:{}:lease", command_id);
1870 let _ = self.kv.delete(&key, None).await;
1871 Ok(())
1872 }
1873
1874 pub async fn reap_expired_commands(&self) -> Result<u32> {
1886 let now = self.now();
1887 let mut expired = 0u32;
1888 let mut cursor: Option<String> = None;
1889 for _ in 0..64 {
1894 let scan = self
1895 .kv
1896 .scan_prefix("deadline:", Some(256), cursor.clone())
1897 .await
1898 .into_alien_error()
1899 .context(ErrorData::KvOperationFailed {
1900 operation: "scan_prefix".to_string(),
1901 key: "deadline:".to_string(),
1902 message: "Failed to scan the deadline index".to_string(),
1903 })?;
1904 let next_cursor = scan.next_cursor.clone();
1905 for entry in scan.items {
1906 let Ok(data) = serde_json::from_slice::<DeadlineIndexData>(&entry.value) else {
1907 warn!(key = %entry.key, "Unparseable deadline index entry; deleting");
1908 let _ = self.kv.delete(&entry.key, None).await;
1909 continue;
1910 };
1911 if data.deadline > now {
1912 continue;
1915 }
1916
1917 let status = self
1918 .command_registry
1919 .get_command_status(&data.command_id)
1920 .await?;
1921 match status {
1922 None => {
1923 let _ = self.kv.delete(&entry.key, None).await;
1924 }
1925 Some(status) if status.state.is_terminal() => {
1926 let _ = self.kv.delete(&entry.key, None).await;
1927 }
1928 Some(status) => {
1929 let won = self
1930 .command_registry
1931 .complete_command(
1932 &data.command_id,
1933 CommandState::Expired,
1934 now,
1935 None,
1936 Some(serde_json::json!({
1937 "code": "COMMAND_EXPIRED",
1938 "message": format!("Deadline {} elapsed", data.deadline.to_rfc3339()),
1939 })),
1940 )
1941 .await?;
1942 if won {
1943 expired += 1;
1944 info!(command_id = %data.command_id, "Expired overdue command");
1945 let _ = self.delete_lease(&data.command_id).await;
1946 let _ = self
1947 .delete_pending_index(
1948 &status.deployment_id,
1949 &status.target.resource_id,
1950 &data.command_id,
1951 )
1952 .await;
1953 }
1954 let _ = self.kv.delete(&entry.key, None).await;
1955 }
1956 }
1957 }
1958 match next_cursor {
1959 Some(next) => cursor = Some(next),
1960 None => break,
1961 }
1962 }
1963 Ok(expired)
1964 }
1965
1966 async fn create_deadline_index(&self, command_id: &str, deadline: DateTime<Utc>) -> Result<()> {
1969 let key = format!(
1970 "deadline:{}:{}",
1971 deadline.timestamp_nanos_opt().unwrap_or(0),
1972 command_id
1973 );
1974
1975 let data = DeadlineIndexData {
1976 command_id: command_id.to_string(),
1977 deadline,
1978 };
1979 let value = serde_json::to_vec(&data).into_alien_error().context(
1980 ErrorData::SerializationFailed {
1981 message: "Failed to serialize deadline index".to_string(),
1982 data_type: Some("DeadlineIndexData".to_string()),
1983 },
1984 )?;
1985
1986 const DEADLINE_INDEX_GRACE: chrono::Duration = chrono::Duration::days(7);
1993 let ttl = deadline
1994 .signed_duration_since(self.now())
1995 .checked_add(&DEADLINE_INDEX_GRACE)
1996 .unwrap_or(DEADLINE_INDEX_GRACE);
1997 let options = (ttl.num_seconds() > 0).then(|| PutOptions {
1998 ttl: Some(Duration::from_secs(ttl.num_seconds() as u64)),
1999 condition: PutCondition::None,
2000 });
2001
2002 self.kv
2003 .put(&key, value, options)
2004 .await
2005 .context(ErrorData::KvOperationFailed {
2006 operation: "put".to_string(),
2007 key: key.clone(),
2008 message: "Failed to create deadline index".to_string(),
2009 })?;
2010 Ok(())
2011 }
2012
2013 async fn dispatch_command_push(
2016 &self,
2017 command_id: &str,
2018 deployment_id: &str,
2019 ) -> Result<CommandState> {
2020 let metadata = self
2022 .command_registry
2023 .get_command_metadata(command_id)
2024 .await?
2025 .ok_or_else(|| {
2026 AlienError::new(ErrorData::CommandNotFound {
2027 command_id: command_id.to_string(),
2028 })
2029 })?;
2030
2031 let params = self.get_params(command_id).await?.ok_or_else(|| {
2033 AlienError::new(ErrorData::CommandNotFound {
2034 command_id: command_id.to_string(),
2035 })
2036 })?;
2037
2038 let envelope = self
2040 .build_envelope(command_id, &metadata, params, None, None, None)
2041 .await?;
2042
2043 if !self
2049 .command_registry
2050 .mark_dispatched_if_not_terminal(command_id, self.now())
2051 .await?
2052 {
2053 return Ok(self
2054 .command_registry
2055 .get_command_status(command_id)
2056 .await?
2057 .map(|status| status.state)
2058 .unwrap_or(CommandState::Dispatched));
2059 }
2060
2061 if let Err(error) = self.command_dispatcher.dispatch(&envelope).await {
2069 if is_definite_dispatch_rejection(&error) {
2070 let delivery_failure = CommandResponse::error(
2071 "DELIVERY_FAILED",
2072 "Worker runtime did not accept command delivery",
2073 );
2074 self.submit_command_response(command_id, delivery_failure)
2075 .await?;
2076 warn!(
2077 command_id,
2078 deployment_id,
2079 error = %error,
2080 "Push dispatch was definitely rejected; command marked Failed"
2081 );
2082 return Ok(CommandState::Failed);
2083 }
2084
2085 let error = error.context(ErrorData::TransportDispatchFailed {
2086 message: "Failed to dispatch command".to_string(),
2087 transport_type: None,
2088 target: Some(deployment_id.to_string()),
2089 });
2090 warn!(
2091 command_id,
2092 deployment_id,
2093 error = %error,
2094 "Push dispatch acknowledgement failed; command remains Dispatched for a possible late response"
2095 );
2096 return Ok(CommandState::Dispatched);
2097 }
2098
2099 info!("Command {} dispatched via push", envelope.command_id);
2100 Ok(CommandState::Dispatched)
2101 }
2102
2103 async fn build_envelope(
2104 &self,
2105 command_id: &str,
2106 metadata: &CommandEnvelopeData,
2107 mut params: BodySpec,
2108 authority_deadline: Option<DateTime<Utc>>,
2109 response_deadline: Option<DateTime<Utc>>,
2110 lease_id: Option<&str>,
2111 ) -> Result<Envelope> {
2112 let response_handling = self
2116 .create_response_handling(command_id, response_deadline, lease_id)
2117 .await?;
2118
2119 if let BodySpec::Storage { size, .. } = ¶ms {
2122 let raw_size = size.unwrap_or(0) as usize;
2123 if raw_size > 0 && raw_size <= self.inline_max_bytes {
2124 let blob_path = StoragePath::from(format!("arc/commands/{}/params", command_id));
2125 match self.storage.get(&blob_path).await {
2126 Ok(get_result) => match get_result.bytes().await {
2127 Ok(raw_bytes) => {
2128 params = BodySpec::inline(&raw_bytes);
2129 debug!(
2130 "Re-inlined params for command {} ({} bytes) into envelope",
2131 command_id, raw_size
2132 );
2133 }
2134 Err(e) => {
2135 debug!(
2136 "Failed to read blob bytes for re-inline (command {}), falling back to presigned URL: {}",
2137 command_id, e
2138 );
2139 }
2140 },
2141 Err(e) => {
2142 debug!(
2143 "Failed to read blob for re-inline (command {}), falling back to presigned URL: {}",
2144 command_id, e
2145 );
2146 }
2147 }
2148 }
2149 }
2150
2151 if let BodySpec::Storage {
2156 size,
2157 storage_get_request: _,
2158 storage_put_used,
2159 } = ¶ms
2160 {
2161 let get_request = self
2162 .generate_storage_get_request_with_deadline(command_id, authority_deadline)
2163 .await?;
2164 params = BodySpec::Storage {
2165 size: *size,
2166 storage_get_request: Some(get_request),
2167 storage_put_used: *storage_put_used,
2168 };
2169 }
2170
2171 Ok(Envelope::new(
2172 metadata.deployment_id.clone(),
2173 metadata.target.clone(),
2174 command_id.to_string(),
2175 metadata.attempt,
2176 metadata.deadline,
2177 metadata.command.clone(),
2178 params,
2179 response_handling,
2180 ))
2181 }
2182
2183 pub async fn refresh_response_handling(
2186 &self,
2187 command_id: &str,
2188 lease_id: &str,
2189 authority_deadline: Option<DateTime<Utc>>,
2190 ) -> Result<ResponseHandling> {
2191 let command = self
2192 .command_registry
2193 .get_command_metadata(command_id)
2194 .await?
2195 .ok_or_else(|| {
2196 AlienError::new(ErrorData::CommandNotFound {
2197 command_id: command_id.into(),
2198 })
2199 })?;
2200 if command.state != CommandState::Dispatched {
2201 return Err(AlienError::new(ErrorData::InvalidCommand {
2202 message: "Response credentials require a dispatched command".into(),
2203 }));
2204 }
2205 let key = format!("cmd:{command_id}:lease");
2206 let entry = self
2207 .kv
2208 .get(&key)
2209 .await
2210 .context(ErrorData::KvOperationFailed {
2211 operation: "get".into(),
2212 key: key.clone(),
2213 message: "Failed to read response lease".into(),
2214 })?
2215 .ok_or_else(|| {
2216 AlienError::new(ErrorData::LeaseNotFound {
2217 lease_id: lease_id.into(),
2218 })
2219 })?;
2220 let lease: LeaseData = serde_json::from_slice(&entry.value)
2221 .into_alien_error()
2222 .context(ErrorData::SerializationFailed {
2223 message: "Failed to decode response lease".into(),
2224 data_type: Some("LeaseData".into()),
2225 })?;
2226 if lease.lease_id != lease_id
2227 || lease.owner != command.deployment_id
2228 || lease.expires_at <= self.now()
2229 {
2230 return Err(AlienError::new(ErrorData::LeaseNotFound {
2231 lease_id: lease_id.into(),
2232 }));
2233 }
2234 let deadline =
2235 authority_deadline.map_or(lease.expires_at, |deadline| deadline.min(lease.expires_at));
2236 let handling = self
2237 .create_response_handling(command_id, Some(deadline), Some(lease_id))
2238 .await?;
2239 let current = self
2240 .kv
2241 .get(&key)
2242 .await
2243 .context(ErrorData::KvOperationFailed {
2244 operation: "get".into(),
2245 key,
2246 message: "Failed to recheck response lease".into(),
2247 })?;
2248 if self.now() >= deadline || current.is_none_or(|current| current.version != entry.version)
2249 {
2250 return Err(AlienError::new(ErrorData::LeaseNotFound {
2251 lease_id: lease_id.into(),
2252 }));
2253 }
2254 Ok(handling)
2255 }
2256
2257 async fn create_response_handling(
2258 &self,
2259 command_id: &str,
2260 authority_deadline: Option<DateTime<Utc>>,
2261 lease_id: Option<&str>,
2262 ) -> Result<ResponseHandling> {
2263 let upload_path = StoragePath::from(format!("arc/commands/{}/response", command_id));
2264 let default_deadline =
2265 self.now() + chrono::Duration::seconds(Self::RESPONSE_CREDENTIAL_LIFETIME_SECS as i64);
2266 let deadline =
2267 authority_deadline.map_or(default_deadline, |deadline| deadline.min(default_deadline));
2268 let expires_in = self.remaining_authority(deadline)?;
2269 let presigned = self
2270 .storage
2271 .presigned_put(&upload_path, expires_in)
2272 .await
2273 .context(ErrorData::StorageOperationFailed {
2274 message: "Failed to create response upload URL".to_string(),
2275 operation: Some("presigned_put".to_string()),
2276 path: Some(upload_path.to_string()),
2277 })?;
2278
2279 self.check_storage_deadline(&presigned, deadline)?;
2280 let (response_token, expires) = self.sign_response_url(command_id, lease_id, deadline);
2281
2282 Ok(ResponseHandling {
2283 max_inline_bytes: self.inline_max_bytes as u64,
2284 submit_response_url: format!(
2285 "{}/commands/{}/response?response_token={}&expires={}{}",
2286 self.base_url.trim_end_matches('/'),
2287 command_id,
2288 response_token,
2289 expires,
2290 lease_id
2291 .map(|lease_id| format!("&lease_id={lease_id}"))
2292 .unwrap_or_default(),
2293 ),
2294 storage_upload_request: presigned,
2295 })
2296 }
2297
2298 async fn generate_params_upload(&self, command_id: &str) -> Result<StorageUpload> {
2299 let upload_path = StoragePath::from(format!("arc/commands/{}/params", command_id));
2300 let expires_in = Duration::from_secs(3600);
2301 let presigned = self
2302 .storage
2303 .presigned_put(&upload_path, expires_in)
2304 .await
2305 .into_alien_error()
2306 .context(ErrorData::StorageOperationFailed {
2307 message: "Failed to create presigned URL".to_string(),
2308 operation: Some("presigned_put".to_string()),
2309 path: Some(upload_path.to_string()),
2310 })?;
2311
2312 Ok(StorageUpload {
2313 put_request: presigned.clone(),
2314 expires_at: presigned.expiration,
2315 })
2316 }
2317
2318 async fn generate_storage_get_request(&self, command_id: &str) -> Result<PresignedRequest> {
2319 self.generate_storage_get_request_with_deadline(command_id, None)
2320 .await
2321 }
2322
2323 async fn generate_storage_get_request_with_deadline(
2324 &self,
2325 command_id: &str,
2326 authority_deadline: Option<DateTime<Utc>>,
2327 ) -> Result<PresignedRequest> {
2328 let path = StoragePath::from(format!("arc/commands/{}/params", command_id));
2329 let default_deadline = self.now() + chrono::Duration::hours(1);
2330 let deadline =
2331 authority_deadline.map_or(default_deadline, |deadline| deadline.min(default_deadline));
2332 let expires_in = self.remaining_authority(deadline)?;
2333 let request = self
2334 .storage
2335 .presigned_get(&path, expires_in)
2336 .await
2337 .context(ErrorData::StorageOperationFailed {
2338 message: "Failed to create storage get request".to_string(),
2339 operation: Some("presigned_get".to_string()),
2340 path: Some(path.to_string()),
2341 })?;
2342 self.check_storage_deadline(&request, deadline)?;
2343 Ok(request)
2344 }
2345
2346 async fn generate_response_storage_get_request(
2347 &self,
2348 command_id: &str,
2349 ) -> Result<PresignedRequest> {
2350 let path = StoragePath::from(format!("arc/commands/{}/response", command_id));
2351 let expires_in = Duration::from_secs(3600);
2352 self.storage.presigned_get(&path, expires_in).await.context(
2353 ErrorData::StorageOperationFailed {
2354 message: "Failed to create response storage get request".to_string(),
2355 operation: Some("presigned_get".to_string()),
2356 path: Some(path.to_string()),
2357 },
2358 )
2359 }
2360
2361 fn extract_command_id_from_index_key(&self, index_key: &str) -> Result<String> {
2362 index_key
2363 .split(':')
2364 .last()
2365 .ok_or_else(|| {
2366 AlienError::new(ErrorData::Other {
2367 message: format!("Invalid index key format: {}", index_key),
2368 })
2369 })
2370 .map(|s| s.to_string())
2371 }
2372}
2373
2374fn validate_operation_result_contract_request(
2375 command: &str,
2376 contract_present: bool,
2377 registry_supports_contract: bool,
2378) -> Result<()> {
2379 let operation_command = command.strip_prefix("operation/v1/").is_some_and(|digest| {
2380 digest.len() == 64
2381 && digest
2382 .bytes()
2383 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
2384 });
2385 if operation_command && !contract_present {
2386 return Err(AlienError::new(ErrorData::InvalidCommand {
2387 message: "Version-qualified operation commands require an immutable result contract"
2388 .to_string(),
2389 }));
2390 }
2391 if contract_present && (!operation_command || !registry_supports_contract) {
2392 return Err(AlienError::new(ErrorData::InvalidCommand {
2393 message:
2394 "This command registry cannot persist the operation result contract before dispatch"
2395 .to_string(),
2396 }));
2397 }
2398 Ok(())
2399}
2400
2401#[cfg(test)]
2402mod relative_url_tests {
2403 use super::*;
2404 use alien_core::presigned::PresignedOperation;
2405 use std::collections::HashMap;
2406
2407 fn http_request(url: &str, operation: PresignedOperation) -> PresignedRequest {
2408 PresignedRequest::new_http(
2409 url.to_string(),
2410 match operation {
2411 PresignedOperation::Get => "GET",
2412 PresignedOperation::Put => "PUT",
2413 PresignedOperation::Delete => "DELETE",
2414 }
2415 .to_string(),
2416 HashMap::new(),
2417 operation,
2418 "commands/test".to_string(),
2419 Utc::now() + chrono::Duration::minutes(5),
2420 )
2421 }
2422
2423 #[test]
2424 fn leased_manager_urls_are_relative_to_lease_endpoint() {
2425 let mut envelope = Envelope::new(
2426 "deployment",
2427 CommandTarget::new("daemon", CommandTargetType::Daemon),
2428 "command",
2429 1,
2430 None,
2431 "run",
2432 BodySpec::Storage {
2433 size: Some(2048),
2434 storage_get_request: Some(http_request(
2435 "http://manager.internal/storage/params?signature=params",
2436 PresignedOperation::Get,
2437 )),
2438 storage_put_used: Some(true),
2439 },
2440 ResponseHandling {
2441 max_inline_bytes: 1024,
2442 submit_response_url:
2443 "http://manager.internal/v1/commands/command/response?response_token=DoNotCanonicalize%2FValue&expires=1"
2444 .to_string(),
2445 storage_upload_request: http_request(
2446 "http://manager.internal/v1/storage/response?signature=DoNotCanonicalize%2FUpload",
2447 PresignedOperation::Put,
2448 ),
2449 },
2450 );
2451
2452 CommandServer::relativize_manager_urls(&mut envelope, "http://manager.internal/v1");
2453
2454 assert_eq!(
2455 envelope.response_handling.submit_response_url,
2456 "command/response?response_token=DoNotCanonicalize%2FValue&expires=1"
2457 );
2458 assert_eq!(
2459 envelope.response_handling.storage_upload_request.url(),
2460 "../storage/response?signature=DoNotCanonicalize%2FUpload"
2461 );
2462 let BodySpec::Storage {
2463 storage_get_request: Some(params),
2464 ..
2465 } = &envelope.params
2466 else {
2467 panic!("storage params request");
2468 };
2469 assert_eq!(params.url(), "../../storage/params?signature=params");
2470
2471 envelope.response_handling.storage_upload_request = http_request(
2472 "https://storage.example.com/result?signature=cloud",
2473 PresignedOperation::Put,
2474 );
2475 CommandServer::relativize_manager_urls(&mut envelope, "http://manager.internal/v1");
2476 assert_eq!(
2477 envelope.response_handling.storage_upload_request.url(),
2478 "https://storage.example.com/result?signature=cloud",
2479 "cloud-presigned URLs must remain byte-for-byte absolute"
2480 );
2481 }
2482}
2483
2484#[cfg(test)]
2485mod idempotency_key_tests {
2486 use super::*;
2487 use crate::server::{validate_command_name, validate_command_target_id};
2488
2489 #[test]
2490 fn storage_key_preserves_portable_legacy_keys_and_encodes_versioned_commands() {
2491 let legacy = CommandServer::compose_idempotency_key("dep", "operator", "refresh", "retry");
2492 assert_eq!(
2493 CommandServer::storage_idempotency_key(&legacy),
2494 "idem:dep:operator:refresh:retry"
2495 );
2496
2497 let versioned =
2498 CommandServer::compose_idempotency_key("dep", "operator", "operation/v1/abc", "retry");
2499 let encoded = CommandServer::storage_idempotency_key(&versioned);
2500 assert!(encoded.starts_with("idem2:"));
2501 assert!(validate_key(&encoded).is_ok());
2502 assert_eq!(encoded, CommandServer::storage_idempotency_key(&versioned));
2503 assert_ne!(
2504 encoded,
2505 CommandServer::storage_idempotency_key(&CommandServer::compose_idempotency_key(
2506 "dep",
2507 "operator",
2508 "operation/v1/def",
2509 "retry",
2510 )),
2511 );
2512 }
2513
2514 #[test]
2515 fn definite_dispatch_rejection_is_classified_by_typed_error_data() {
2516 let rejected = AlienError::new(ErrorData::TransportDispatchRejected {
2517 message: "not accepted".to_string(),
2518 transport_type: Some("http".to_string()),
2519 target: Some("command-id".to_string()),
2520 });
2521 assert!(is_definite_dispatch_rejection(&rejected));
2522
2523 let ambiguous = AlienError::new(ErrorData::TransportDispatchFailed {
2524 message: "acknowledgement lost".to_string(),
2525 transport_type: Some("http".to_string()),
2526 target: Some("command-id".to_string()),
2527 });
2528 assert!(!is_definite_dispatch_rejection(&ambiguous));
2529 }
2530
2531 #[test]
2540 fn target_id_colon_guard_prevents_idempotency_key_collision() {
2541 let colliding = CommandServer::compose_idempotency_key("dep", "svc", "a:b", "k");
2542 assert_eq!(colliding, "dep:svc:a:b:k");
2543
2544 assert!(
2546 validate_command_target_id("svc:a").is_err(),
2547 "a ':'-bearing target id must be rejected so it cannot forge the rid segment"
2548 );
2549 assert!(validate_command_target_id("svc").is_ok());
2550 }
2551
2552 #[test]
2560 fn command_name_colon_guard_prevents_idempotency_key_collision() {
2561 let forged = CommandServer::compose_idempotency_key("dep", "svc", "a:b", "c");
2563 let legitimate = CommandServer::compose_idempotency_key("dep", "svc", "a", "b:c");
2564 assert_eq!(
2565 forged, legitimate,
2566 "these inputs are exactly the colliding pair the guard must separate"
2567 );
2568 assert_eq!(legitimate, "dep:svc:a:b:c");
2569
2570 let err = validate_command_name("a:b").expect_err("':'-bearing command must be rejected");
2575 assert_eq!(err.code, "INVALID_COMMAND");
2576 assert!(validate_command_name("a").is_ok());
2577 }
2578
2579 #[test]
2580 fn versioned_operation_requires_atomic_result_contract_support() {
2581 let command = format!("operation/v1/{}", "a".repeat(64));
2582
2583 assert!(validate_operation_result_contract_request(&command, true, true).is_ok());
2584 assert!(validate_operation_result_contract_request(&command, false, true).is_err());
2585 assert!(validate_operation_result_contract_request(&command, true, false).is_err());
2586 assert!(validate_operation_result_contract_request("postgres/health", true, true).is_err());
2587 }
2588}