1use std::time::{Duration, Instant};
2
3use alien_core::{presigned::redact_url_for_error, MessagePayload, QueueMessage};
4use alien_error::{AlienError, Context, ContextError, IntoAlienError, IntoAlienErrorDirect};
5use chrono::{DateTime, Utc};
6use tracing::debug;
7
8use crate::{
9 error::{Error, ErrorData, Result},
10 resolve_envelope_urls,
11 types::{BodySpec, CommandResponse, Envelope, LeaseInfo, LeaseRequest, LeaseResponse},
12 PROTOCOL_VERSION,
13};
14
15pub const LEASE_SAFETY_MARGIN: Duration = Duration::from_secs(5);
22
23pub(crate) const COMMAND_RESPONSE_SUBMISSION_TIMEOUT: Duration = Duration::from_secs(30);
26
27pub fn command_budget(
36 deadline: Option<DateTime<Utc>>,
37 lease_expires_at: DateTime<Utc>,
38) -> DateTime<Utc> {
39 let margin = chrono::Duration::from_std(LEASE_SAFETY_MARGIN)
40 .unwrap_or_else(|_| chrono::Duration::seconds(5));
41 let lease_bound = (lease_expires_at - margin).max(Utc::now());
42 deadline.map_or(lease_bound, |d| d.min(lease_bound))
43}
44
45pub fn parse_envelope(message: &QueueMessage) -> Result<Option<Envelope>> {
47 let envelope_data = match &message.payload {
48 MessagePayload::Json(value) => {
49 match serde_json::from_value::<Envelope>(value.clone()) {
51 Ok(envelope) => envelope,
52 Err(_) => return Ok(None), }
54 }
55 MessagePayload::Text(text) => {
56 match serde_json::from_str::<Envelope>(text) {
58 Ok(envelope) => envelope,
59 Err(_) => return Ok(None), }
61 }
62 };
63
64 if envelope_data.protocol != PROTOCOL_VERSION {
66 return Ok(None);
67 }
68
69 envelope_data
70 .validate()
71 .context(ErrorData::InvalidEnvelope {
72 message: "Envelope validation failed".to_string(),
73 field: None,
74 })?;
75 Ok(Some(envelope_data))
76}
77
78pub async fn decode_params(envelope: &Envelope) -> Result<serde_json::Value> {
83 match &envelope.params {
84 BodySpec::Inline { inline_base64 } => {
85 use base64::{engine::general_purpose, Engine as _};
86
87 let bytes = general_purpose::STANDARD
88 .decode(inline_base64)
89 .into_alien_error()
90 .context(ErrorData::InvalidEnvelope {
91 message: "Failed to decode base64 params".to_string(),
92 field: Some("params.inlineBase64".to_string()),
93 })?;
94
95 serde_json::from_slice(&bytes)
96 .into_alien_error()
97 .context(ErrorData::InvalidEnvelope {
98 message: "Failed to parse params JSON".to_string(),
99 field: Some("params".to_string()),
100 })
101 }
102 BodySpec::Storage {
103 storage_get_request,
104 ..
105 } => {
106 let presigned_request = storage_get_request.as_ref().ok_or_else(|| {
107 AlienError::new(ErrorData::InvalidEnvelope {
108 message: "Storage params missing storage_get_request".to_string(),
109 field: Some("params.storageGetRequest".to_string()),
110 })
111 })?;
112
113 let response = presigned_request.execute(None).await.context(
114 ErrorData::StorageOperationFailed {
115 message: "Failed to fetch params from storage".to_string(),
116 operation: Some("get".to_string()),
117 path: Some(presigned_request.path.clone()),
118 },
119 )?;
120
121 let body = response.body.ok_or_else(|| {
122 AlienError::new(ErrorData::StorageOperationFailed {
123 message: "Storage response has no body".to_string(),
124 operation: Some("get".to_string()),
125 path: Some(presigned_request.path.clone()),
126 })
127 })?;
128
129 serde_json::from_slice(&body)
130 .into_alien_error()
131 .context(ErrorData::InvalidEnvelope {
132 message: "Failed to parse params JSON from storage".to_string(),
133 field: Some("params".to_string()),
134 })
135 }
136 }
137}
138
139pub async fn decode_params_bytes(envelope: &Envelope) -> Result<Vec<u8>> {
144 match &envelope.params {
145 BodySpec::Inline { inline_base64 } => {
146 use base64::{engine::general_purpose, Engine as _};
147
148 general_purpose::STANDARD
149 .decode(inline_base64)
150 .into_alien_error()
151 .context(ErrorData::InvalidEnvelope {
152 message: "Failed to decode base64 params".to_string(),
153 field: Some("params.inlineBase64".to_string()),
154 })
155 }
156 BodySpec::Storage {
157 storage_get_request,
158 ..
159 } => {
160 let presigned_request = storage_get_request.as_ref().ok_or_else(|| {
161 AlienError::new(ErrorData::InvalidEnvelope {
162 message: "Storage params missing storage_get_request".to_string(),
163 field: Some("params.storageGetRequest".to_string()),
164 })
165 })?;
166
167 let response = presigned_request.execute(None).await.context(
168 ErrorData::StorageOperationFailed {
169 message: "Failed to fetch params from storage".to_string(),
170 operation: Some("get".to_string()),
171 path: Some(presigned_request.path.clone()),
172 },
173 )?;
174
175 response.body.map(|b| b.to_vec()).ok_or_else(|| {
176 AlienError::new(ErrorData::StorageOperationFailed {
177 message: "Storage response has no body".to_string(),
178 operation: Some("get".to_string()),
179 path: Some(presigned_request.path.clone()),
180 })
181 })
182 }
183 }
184}
185
186#[cfg(any(feature = "runtime", feature = "receiver"))]
192pub async fn submit_response(envelope: &Envelope, response: CommandResponse) -> Result<()> {
193 submit_response_with_timeout(envelope, response, COMMAND_RESPONSE_SUBMISSION_TIMEOUT).await
194}
195
196#[cfg(feature = "receiver")]
203pub(crate) async fn submit_response_before(
204 envelope: &Envelope,
205 response: CommandResponse,
206 lease_expires_at: DateTime<Utc>,
207) -> Result<()> {
208 let remaining_lease = (lease_expires_at - Utc::now())
209 .to_std()
210 .unwrap_or(Duration::ZERO);
211 submit_response_with_timeout(
212 envelope,
213 response,
214 COMMAND_RESPONSE_SUBMISSION_TIMEOUT.min(remaining_lease),
215 )
216 .await
217}
218
219#[cfg(any(feature = "runtime", feature = "receiver"))]
220async fn submit_response_with_timeout(
221 envelope: &Envelope,
222 response: CommandResponse,
223 timeout: Duration,
224) -> Result<()> {
225 let operation = async {
226 let start_time = Instant::now();
227 let client = reqwest::Client::builder()
228 .timeout(COMMAND_RESPONSE_SUBMISSION_TIMEOUT)
229 .pool_max_idle_per_host(2)
230 .pool_idle_timeout(Some(Duration::from_secs(60)))
231 .build()
232 .into_alien_error()
233 .context(ErrorData::Other {
234 message: "Failed to create HTTP client".to_string(),
235 })?;
236 let (final_response, mut pending_upload) = prepare_response_submission(envelope, response)?;
237 let mut retry_delay = Duration::from_millis(100);
238 loop {
239 match submit_response_attempt(&client, envelope, &final_response, &mut pending_upload)
240 .await
241 {
242 Ok(()) => {
243 debug!(
244 command_id = %envelope.command_id,
245 processing_ms = start_time.elapsed().as_millis(),
246 response_type = if final_response.is_success() { "success" } else { "error" },
247 "Command response submitted successfully"
248 );
249 return Ok(());
250 }
251 Err(SubmissionAttemptError::Permanent(error)) => return Err(error),
252 Err(SubmissionAttemptError::Retryable(error)) => {
253 debug!(
254 command_id = %envelope.command_id,
255 error_code = %error.code,
256 retry_delay_ms = retry_delay.as_millis(),
257 "Transient command response submission failure; retrying"
258 );
259 tokio::time::sleep(retry_delay).await;
260 retry_delay = (retry_delay * 2).min(Duration::from_secs(1));
261 }
262 }
263 }
264 };
265
266 match tokio::time::timeout(timeout, operation).await {
267 Ok(result) => result,
268 Err(error) => Err(error
269 .into_alien_error()
270 .context(ErrorData::HttpOperationFailed {
271 message: format!(
272 "Command response upload/submission exceeded its {} ms headroom budget",
273 timeout.as_millis()
274 ),
275 method: None,
276 url: Some(redact_url_for_error(
277 &envelope.response_handling.submit_response_url,
278 )),
279 })),
280 }
281}
282
283#[cfg(any(feature = "runtime", feature = "receiver"))]
284enum SubmissionAttemptError {
285 Retryable(Error),
286 Permanent(Error),
287}
288
289#[cfg(any(feature = "runtime", feature = "receiver"))]
290fn prepare_response_submission(
291 envelope: &Envelope,
292 response: CommandResponse,
293) -> Result<(CommandResponse, Option<bytes::Bytes>)> {
294 match &response {
295 CommandResponse::Success { response: body } => {
296 let body_size = body.size().unwrap_or(0);
297
298 if body_size > envelope.response_handling.max_inline_bytes {
299 let body_bytes = body.decode_inline().ok_or_else(|| {
300 AlienError::new(ErrorData::Other {
301 message: "Cannot upload storage body - expected inline body".to_string(),
302 })
303 })?;
304 Ok((
305 CommandResponse::Success {
306 response: BodySpec::Storage {
307 size: Some(body_bytes.len() as u64),
308 storage_get_request: None,
309 storage_put_used: Some(true),
310 },
311 },
312 Some(bytes::Bytes::from(body_bytes)),
313 ))
314 } else {
315 Ok((response, None))
316 }
317 }
318 CommandResponse::Error { .. } => Ok((response, None)),
319 }
320}
321
322#[cfg(any(feature = "runtime", feature = "receiver"))]
323async fn submit_response_attempt(
324 client: &reqwest::Client,
325 envelope: &Envelope,
326 final_response: &CommandResponse,
327 pending_upload: &mut Option<bytes::Bytes>,
328) -> std::result::Result<(), SubmissionAttemptError> {
329 if let Some(body_bytes) = pending_upload.as_ref() {
330 debug!(
331 command_id = %envelope.command_id,
332 body_size = body_bytes.len(),
333 max_inline = envelope.response_handling.max_inline_bytes,
334 "Uploading large response body to storage"
335 );
336
337 let upload_result = envelope
338 .response_handling
339 .storage_upload_request
340 .execute_with_client(client, Some(body_bytes.clone()))
341 .await;
342 let upload_response = match upload_result {
343 Ok(response) => response,
344 Err(error) => {
345 let retryable = error.retryable;
346 let error = error.context(ErrorData::StorageOperationFailed {
347 message: "Failed to upload response to storage".to_string(),
348 operation: Some("put".to_string()),
349 path: Some(
350 envelope
351 .response_handling
352 .storage_upload_request
353 .path
354 .clone(),
355 ),
356 });
357 return Err(if retryable {
358 SubmissionAttemptError::Retryable(error)
359 } else {
360 SubmissionAttemptError::Permanent(error)
361 });
362 }
363 };
364
365 if upload_response.status_code < 200 || upload_response.status_code >= 300 {
366 let status = upload_response.status_code;
367 let error = AlienError::new(ErrorData::StorageOperationFailed {
368 message: format!("Storage upload failed with status {}", status),
369 operation: Some("put".to_string()),
370 path: Some(
371 envelope
372 .response_handling
373 .storage_upload_request
374 .path
375 .clone(),
376 ),
377 });
378 return Err(if status == 408 || status == 429 || status >= 500 {
379 SubmissionAttemptError::Retryable(error)
380 } else {
381 SubmissionAttemptError::Permanent(error)
382 });
383 }
384
385 debug!(
386 command_id = %envelope.command_id,
387 upload_status = upload_response.status_code,
388 "Response body uploaded to storage successfully"
389 );
390 *pending_upload = None;
391 }
392
393 let submit_url = &envelope.response_handling.submit_response_url;
395 let safe_submit_url = redact_url_for_error(submit_url);
396
397 debug!(
398 command_id = %envelope.command_id,
399 url = %safe_submit_url,
400 "Submitting command response"
401 );
402
403 let http_response = client
404 .put(submit_url)
405 .json(&crate::types::SubmitResponseRequest {
406 response: final_response.clone(),
407 })
408 .send()
409 .await;
410 let http_response =
411 match http_response {
412 Ok(response) => response,
413 Err(error) => {
414 let retryable = !error.is_builder();
415 let error = error.without_url().into_alien_error().context(
416 ErrorData::HttpOperationFailed {
417 message: "Failed to submit response".to_string(),
418 method: Some("PUT".to_string()),
419 url: Some(safe_submit_url.clone()),
420 },
421 );
422 return Err(if retryable {
423 SubmissionAttemptError::Retryable(error)
424 } else {
425 SubmissionAttemptError::Permanent(error)
426 });
427 }
428 };
429
430 if !http_response.status().is_success()
431 && http_response.status() != reqwest::StatusCode::CONFLICT
432 && http_response.status() != reqwest::StatusCode::GONE
433 {
434 let status = http_response.status();
435 let error = AlienError::new(ErrorData::HttpOperationFailed {
436 message: format!("Response submission failed with status {status}"),
439 method: Some("PUT".to_string()),
440 url: Some(safe_submit_url),
441 });
442 return Err(
443 if status == reqwest::StatusCode::REQUEST_TIMEOUT
444 || status == reqwest::StatusCode::TOO_MANY_REQUESTS
445 || status.is_server_error()
446 {
447 SubmissionAttemptError::Retryable(error)
448 } else {
449 SubmissionAttemptError::Permanent(error)
450 },
451 );
452 }
453
454 Ok(())
455}
456
457#[cfg(any(feature = "runtime", feature = "receiver"))]
468#[derive(Debug, Clone)]
469pub struct LeaseClient {
470 client: reqwest::Client,
471 endpoint: reqwest::Url,
472 token: String,
473}
474
475#[cfg(any(feature = "runtime", feature = "receiver"))]
476impl LeaseClient {
477 pub fn from_base(base: &reqwest::Url, token: String) -> Option<Self> {
484 let mut endpoint = base.clone();
485 endpoint
486 .path_segments_mut()
487 .ok()?
488 .pop_if_empty()
489 .push("commands")
490 .push("leases");
491 let client = reqwest::Client::builder()
496 .redirect(reqwest::redirect::Policy::none())
497 .timeout(Duration::from_secs(30))
498 .build()
499 .ok()?;
500 Some(Self {
501 client,
502 endpoint,
503 token,
504 })
505 }
506
507 pub fn endpoint(&self) -> &reqwest::Url {
509 &self.endpoint
510 }
511
512 pub async fn acquire(&self, request: &LeaseRequest) -> Result<Vec<LeaseInfo>> {
516 self.acquire_with_token(request, &self.token).await
517 }
518
519 pub async fn acquire_with_token(
522 &self,
523 request: &LeaseRequest,
524 token: &str,
525 ) -> Result<Vec<LeaseInfo>> {
526 let response = self
527 .client
528 .post(self.endpoint.clone())
529 .header("Authorization", format!("Bearer {token}"))
530 .json(request)
531 .send()
532 .await
533 .into_alien_error()
534 .context(ErrorData::HttpOperationFailed {
535 message: "Failed to acquire leases".to_string(),
536 method: Some("POST".to_string()),
537 url: Some(self.endpoint.to_string()),
538 })?;
539
540 if response.status() == reqwest::StatusCode::UNAUTHORIZED {
541 return Err(AlienError::new(ErrorData::CommandReceiverUnauthorized {
542 operation: "lease acquisition".to_string(),
543 url: self.endpoint.to_string(),
544 }));
545 }
546
547 if !response.status().is_success() {
548 let status = response.status();
549 if status == reqwest::StatusCode::REQUEST_TIMEOUT
550 || status == reqwest::StatusCode::TOO_MANY_REQUESTS
551 || status.is_server_error()
552 {
553 return Err(AlienError::new(ErrorData::HttpOperationFailed {
554 message: format!("Lease request failed with status {status}"),
555 method: Some("POST".to_string()),
556 url: Some(self.endpoint.to_string()),
557 }));
558 }
559 return Err(AlienError::new(ErrorData::CommandReceiverRequestRejected {
560 operation: "lease acquisition".to_string(),
561 status: status.as_u16(),
562 url: self.endpoint.to_string(),
563 }));
564 }
565
566 let mut lease_response: LeaseResponse =
567 response
568 .json()
569 .await
570 .into_alien_error()
571 .context(ErrorData::SerializationFailed {
572 message: "Failed to parse lease response".to_string(),
573 data_type: Some("LeaseResponse".to_string()),
574 })?;
575
576 for lease in &mut lease_response.leases {
581 resolve_envelope_urls(&mut lease.envelope, &self.endpoint);
582 }
583
584 Ok(lease_response.leases)
585 }
586
587 pub async fn refresh_response_context(
590 &self,
591 envelope: &mut Envelope,
592 lease_id: &str,
593 token: &str,
594 ) -> Result<()> {
595 let mut endpoint = self.endpoint.clone();
596 endpoint
597 .path_segments_mut()
598 .map_err(|_| {
599 AlienError::new(ErrorData::Other {
600 message: "Invalid commands endpoint".into(),
601 })
602 })?
603 .pop()
604 .push(&envelope.command_id)
605 .push("response-context");
606 endpoint.query_pairs_mut().append_pair("leaseId", lease_id);
607 let mut response = self
608 .client
609 .get(endpoint.clone())
610 .bearer_auth(token)
611 .send()
612 .await
613 .map_err(|_| {
614 AlienError::new(ErrorData::HttpOperationFailed {
615 message: "Cannot refresh command response context".into(),
616 method: Some("GET".into()),
617 url: Some(endpoint.to_string()),
618 })
619 })?;
620 let status = response.status();
621 if status == reqwest::StatusCode::UNAUTHORIZED {
622 return Err(AlienError::new(ErrorData::CommandReceiverUnauthorized {
623 operation: "response context refresh".into(),
624 url: endpoint.to_string(),
625 }));
626 }
627 if !status.is_success() {
628 return Err(AlienError::new(ErrorData::CommandReceiverRequestRejected {
629 operation: "response context refresh".into(),
630 status: status.as_u16(),
631 url: endpoint.to_string(),
632 }));
633 }
634 let mut bytes = Vec::new();
635 while let Some(chunk) = response.chunk().await.map_err(|_| {
636 AlienError::new(ErrorData::Other {
637 message: "Cannot read command response context".into(),
638 })
639 })? {
640 if bytes.len() + chunk.len() > 64 * 1024 {
641 return Err(AlienError::new(ErrorData::Other {
642 message: "Command response context exceeds limit".into(),
643 }));
644 }
645 bytes.extend_from_slice(&chunk);
646 }
647 envelope.response_handling = serde_json::from_slice(&bytes).map_err(|_| {
648 AlienError::new(ErrorData::Other {
649 message: "Invalid command response context".into(),
650 })
651 })?;
652 resolve_envelope_urls(envelope, &self.endpoint);
653 Ok(())
654 }
655
656 pub async fn release_with_token(&self, lease_id: &str, token: &str) -> Result<()> {
660 let mut endpoint = self.endpoint.clone();
661 let Ok(mut segments) = endpoint.path_segments_mut() else {
662 return Err(AlienError::new(ErrorData::HttpOperationFailed {
663 message: "Commands lease endpoint cannot be extended for release".to_string(),
664 method: Some("POST".to_string()),
665 url: Some(endpoint.to_string()),
666 }));
667 };
668 segments.push(lease_id).push("release");
669 drop(segments);
670 let response = self
671 .client
672 .post(endpoint.clone())
673 .header("Authorization", format!("Bearer {token}"))
674 .json(&crate::types::ReleaseRequest {
675 lease_id: lease_id.to_string(),
676 })
677 .send()
678 .await
679 .into_alien_error()
680 .context(ErrorData::HttpOperationFailed {
681 message: format!("Failed to release lease '{lease_id}'"),
682 method: Some("POST".to_string()),
683 url: Some(endpoint.to_string()),
684 })?;
685
686 if response.status() == reqwest::StatusCode::UNAUTHORIZED {
687 return Err(AlienError::new(ErrorData::CommandReceiverUnauthorized {
688 operation: "lease release".to_string(),
689 url: endpoint.to_string(),
690 }));
691 }
692 if response.status().is_success()
693 || response.status() == reqwest::StatusCode::CONFLICT
694 || response.status() == reqwest::StatusCode::GONE
695 {
696 return Ok(());
697 }
698
699 let status = response.status();
700 Err(AlienError::new(ErrorData::HttpOperationFailed {
701 message: format!("Lease release failed with status {status}"),
702 method: Some("POST".to_string()),
703 url: Some(endpoint.to_string()),
704 }))
705 }
706}
707
708pub fn create_test_response(data: &[u8]) -> CommandResponse {
710 CommandResponse::success(data)
711}
712
713pub fn create_test_error(code: &str, message: &str) -> CommandResponse {
715 CommandResponse::error(code, message)
716}
717
718#[cfg(test)]
719mod tests {
720 use super::*;
721 use alien_core::presigned::{PresignedOperation, PresignedRequest};
722 use axum::{extract::State, http::StatusCode, routing::post, routing::put, Router};
723 use chrono::Utc;
724 use std::sync::atomic::{AtomicUsize, Ordering};
725 use std::sync::Arc;
726
727 async fn fail_once_then_accept(State(attempts): State<Arc<AtomicUsize>>) -> StatusCode {
728 if attempts.fetch_add(1, Ordering::SeqCst) == 0 {
729 StatusCode::SERVICE_UNAVAILABLE
730 } else {
731 StatusCode::OK
732 }
733 }
734
735 async fn reject_permanently(State(attempts): State<Arc<AtomicUsize>>) -> StatusCode {
736 attempts.fetch_add(1, Ordering::SeqCst);
737 StatusCode::BAD_REQUEST
738 }
739
740 async fn reject_lease_permanently(
741 State(attempts): State<Arc<AtomicUsize>>,
742 ) -> (StatusCode, &'static str) {
743 attempts.fetch_add(1, Ordering::SeqCst);
744 (StatusCode::FORBIDDEN, "sensitive-provider-error-body")
745 }
746
747 async fn reject_lease_transiently(State(attempts): State<Arc<AtomicUsize>>) -> StatusCode {
748 attempts.fetch_add(1, Ordering::SeqCst);
749 StatusCode::SERVICE_UNAVAILABLE
750 }
751
752 #[derive(Clone)]
753 struct UploadThenRetryState {
754 uploads: Arc<AtomicUsize>,
755 submissions: Arc<AtomicUsize>,
756 }
757
758 async fn accept_upload(State(state): State<UploadThenRetryState>) -> StatusCode {
759 state.uploads.fetch_add(1, Ordering::SeqCst);
760 StatusCode::OK
761 }
762
763 async fn fail_first_submission(State(state): State<UploadThenRetryState>) -> StatusCode {
764 if state.submissions.fetch_add(1, Ordering::SeqCst) == 0 {
765 StatusCode::SERVICE_UNAVAILABLE
766 } else {
767 StatusCode::OK
768 }
769 }
770
771 fn create_test_envelope() -> Envelope {
772 Envelope {
773 protocol: PROTOCOL_VERSION.to_string(),
774 target: crate::types::CommandTarget::new(
775 "test-worker",
776 crate::types::CommandTargetType::Worker,
777 ),
778 command_id: "cmd_123".to_string(),
779 attempt: 1,
780 trace_context: None,
781 deadline: None,
782 command: "test-command".to_string(),
783 params: BodySpec::inline(b"{}"),
784 response_handling: crate::types::ResponseHandling {
785 max_inline_bytes: 150000,
786 submit_response_url: "https://commands.example.com/commands/cmd_123/response"
787 .to_string(),
788 storage_upload_request: PresignedRequest::new_http(
789 "https://storage.example.com/upload".to_string(),
790 "PUT".to_string(),
791 std::collections::HashMap::new(),
792 PresignedOperation::Put,
793 "test-path".to_string(),
794 Utc::now() + chrono::Duration::hours(1),
795 ),
796 },
797 deployment_id: "dep_123".to_string(),
798 }
799 }
800
801 #[test]
805 fn resolve_envelope_urls_resolves_relative_and_keeps_absolute() {
806 let base =
807 reqwest::Url::parse("https://edge.example.com/tenant/v1/commands/leases").unwrap();
808
809 let mut envelope = create_test_envelope();
810 envelope.response_handling.submit_response_url =
811 "cmd_123/response?response_token=t&expires=1".to_string();
812 if let alien_core::presigned::PresignedRequestBackend::Http { url, .. } =
813 &mut envelope.response_handling.storage_upload_request.backend
814 {
815 *url = "../storage/response-blob?sig=x".to_string();
816 }
817 envelope.params = BodySpec::Storage {
818 size: Some(2048),
819 storage_get_request: Some(PresignedRequest::new_http(
820 "cmd_123/params?sig=params".to_string(),
821 "GET".to_string(),
822 std::collections::HashMap::new(),
823 PresignedOperation::Get,
824 "commands/cmd_123/params".to_string(),
825 Utc::now() + chrono::Duration::hours(1),
826 )),
827 storage_put_used: Some(true),
828 };
829
830 resolve_envelope_urls(&mut envelope, &base);
831 assert_eq!(
832 envelope.response_handling.submit_response_url,
833 "https://edge.example.com/tenant/v1/commands/cmd_123/response?response_token=t&expires=1",
834 "relative submit URL must retain the endpoint prefix"
835 );
836 match &envelope.response_handling.storage_upload_request.backend {
837 alien_core::presigned::PresignedRequestBackend::Http { url, .. } => {
838 assert_eq!(
839 url,
840 "https://edge.example.com/tenant/v1/storage/response-blob?sig=x"
841 );
842 }
843 other => panic!("unexpected backend: {other:?}"),
844 }
845 let BodySpec::Storage {
846 storage_get_request: Some(params),
847 ..
848 } = &envelope.params
849 else {
850 panic!("storage params request");
851 };
852 assert_eq!(
853 params.url(),
854 "https://edge.example.com/tenant/v1/commands/cmd_123/params?sig=params"
855 );
856
857 let mut envelope = create_test_envelope();
859 let cloud_url = "https://storage.example.com/upload?X-Signature=DoNotCanonicalize%2FValue";
860 if let alien_core::presigned::PresignedRequestBackend::Http { url, .. } =
861 &mut envelope.response_handling.storage_upload_request.backend
862 {
863 *url = cloud_url.to_string();
864 }
865 resolve_envelope_urls(&mut envelope, &base);
866 assert_eq!(
867 envelope.response_handling.submit_response_url,
868 "https://commands.example.com/commands/cmd_123/response"
869 );
870 assert_eq!(
871 envelope.response_handling.storage_upload_request.url(),
872 cloud_url
873 );
874 }
875
876 #[tokio::test]
877 async fn submit_response_error_does_not_expose_response_token() {
878 let secret = "do-not-log-response-token";
879 let mut envelope = create_test_envelope();
880 envelope.response_handling.submit_response_url =
881 format!("http://127.0.0.1:0/response?response_token={secret}&expires=1");
882
883 let error = submit_response_with_timeout(
884 &envelope,
885 create_test_response(b"ok"),
886 Duration::from_millis(50),
887 )
888 .await
889 .expect_err("port zero must reject the response submission");
890 let serialized = serde_json::to_string(&error).unwrap();
891 let debug = format!("{error:?}");
892
893 assert!(
894 !serialized.contains(secret),
895 "serialized error leaked token"
896 );
897 assert!(!debug.contains(secret), "debug error leaked token");
898 assert!(serialized.contains("http://127.0.0.1:0/response"));
899 }
900
901 #[tokio::test]
902 async fn response_upload_and_submit_share_one_bounded_redacted_timeout() {
903 let upload_secret = "do-not-log-upload-signature";
904 let response_secret = "do-not-log-response-token";
905 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
906 let address = listener.local_addr().unwrap();
907 let server = tokio::spawn(async move {
908 let (_socket, _) = listener.accept().await.unwrap();
909 std::future::pending::<()>().await;
910 });
911
912 let mut envelope = create_test_envelope();
913 envelope.response_handling.max_inline_bytes = 1;
914 envelope.response_handling.submit_response_url =
915 format!("http://{address}/response?response_token={response_secret}");
916 envelope.response_handling.storage_upload_request = PresignedRequest::new_http(
917 format!("http://{address}/upload?signature={upload_secret}"),
918 "PUT".to_string(),
919 std::collections::HashMap::new(),
920 PresignedOperation::Put,
921 "test-path".to_string(),
922 Utc::now() + chrono::Duration::hours(1),
923 );
924
925 let error = submit_response_with_timeout(
926 &envelope,
927 create_test_response(b"large-response"),
928 Duration::from_millis(50),
929 )
930 .await
931 .expect_err("blackholed response upload must time out");
932 let serialized = serde_json::to_string(&error).unwrap();
933 let debug = format!("{error:?}");
934
935 for secret in [upload_secret, response_secret] {
936 assert!(
937 !serialized.contains(secret),
938 "serialized error leaked token"
939 );
940 assert!(!debug.contains(secret), "debug error leaked token");
941 }
942 assert!(serialized.contains(&format!("http://{address}/response")));
943 server.abort();
944 }
945
946 #[tokio::test]
947 async fn transient_final_put_is_retried_within_submission_budget() {
948 let attempts = Arc::new(AtomicUsize::new(0));
949 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
950 let address = listener.local_addr().unwrap();
951 let server_attempts = attempts.clone();
952 let server = tokio::spawn(async move {
953 axum::serve(
954 listener,
955 Router::new()
956 .route("/response", put(fail_once_then_accept))
957 .with_state(server_attempts),
958 )
959 .await
960 .unwrap();
961 });
962
963 let mut envelope = create_test_envelope();
964 envelope.response_handling.submit_response_url = format!("http://{address}/response");
965 submit_response_with_timeout(
966 &envelope,
967 create_test_response(b"ok"),
968 Duration::from_secs(2),
969 )
970 .await
971 .expect("second PUT should terminalize the command");
972
973 assert_eq!(attempts.load(Ordering::SeqCst), 2);
974 server.abort();
975 }
976
977 #[tokio::test]
978 async fn retrying_final_put_does_not_repeat_successful_blob_upload() {
979 let state = UploadThenRetryState {
980 uploads: Arc::new(AtomicUsize::new(0)),
981 submissions: Arc::new(AtomicUsize::new(0)),
982 };
983 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
984 let address = listener.local_addr().unwrap();
985 let server_state = state.clone();
986 let server = tokio::spawn(async move {
987 axum::serve(
988 listener,
989 Router::new()
990 .route("/upload", put(accept_upload))
991 .route("/response", put(fail_first_submission))
992 .with_state(server_state),
993 )
994 .await
995 .unwrap();
996 });
997
998 let mut envelope = create_test_envelope();
999 envelope.response_handling.max_inline_bytes = 1;
1000 envelope.response_handling.submit_response_url = format!("http://{address}/response");
1001 envelope.response_handling.storage_upload_request = PresignedRequest::new_http(
1002 format!("http://{address}/upload"),
1003 "PUT".to_string(),
1004 std::collections::HashMap::new(),
1005 PresignedOperation::Put,
1006 "test-path".to_string(),
1007 Utc::now() + chrono::Duration::hours(1),
1008 );
1009
1010 submit_response_with_timeout(
1011 &envelope,
1012 create_test_response(b"large-response"),
1013 Duration::from_secs(2),
1014 )
1015 .await
1016 .expect("retrying the terminal PUT should not re-upload its blob");
1017
1018 assert_eq!(state.uploads.load(Ordering::SeqCst), 1);
1019 assert_eq!(state.submissions.load(Ordering::SeqCst), 2);
1020 server.abort();
1021 }
1022
1023 #[tokio::test]
1024 async fn permanent_final_put_rejection_is_not_retried() {
1025 let attempts = Arc::new(AtomicUsize::new(0));
1026 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1027 let address = listener.local_addr().unwrap();
1028 let server_attempts = attempts.clone();
1029 let server = tokio::spawn(async move {
1030 axum::serve(
1031 listener,
1032 Router::new()
1033 .route("/response", put(reject_permanently))
1034 .with_state(server_attempts),
1035 )
1036 .await
1037 .unwrap();
1038 });
1039
1040 let mut envelope = create_test_envelope();
1041 envelope.response_handling.submit_response_url = format!("http://{address}/response");
1042 let error = submit_response_with_timeout(
1043 &envelope,
1044 create_test_response(b"ok"),
1045 Duration::from_secs(2),
1046 )
1047 .await
1048 .expect_err("400 is a permanent submission rejection");
1049
1050 assert_eq!(attempts.load(Ordering::SeqCst), 1);
1051 assert!(error.message.contains("400"));
1052 server.abort();
1053 }
1054
1055 fn test_lease_request() -> LeaseRequest {
1056 LeaseRequest {
1057 deployment_id: "dep_123".to_string(),
1058 target: crate::types::CommandTarget::new(
1059 "agent",
1060 crate::types::CommandTargetType::Daemon,
1061 ),
1062 max_leases: 1,
1063 lease_seconds: 60,
1064 }
1065 }
1066
1067 #[tokio::test]
1068 async fn permanent_lease_rejection_is_non_retryable_and_redacted() {
1069 let attempts = Arc::new(AtomicUsize::new(0));
1070 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1071 let address = listener.local_addr().unwrap();
1072 let server_attempts = attempts.clone();
1073 let server = tokio::spawn(async move {
1074 axum::serve(
1075 listener,
1076 Router::new()
1077 .route("/commands/leases", post(reject_lease_permanently))
1078 .with_state(server_attempts),
1079 )
1080 .await
1081 .unwrap();
1082 });
1083 let base = reqwest::Url::parse(&format!("http://{address}")).unwrap();
1084 let client = LeaseClient::from_base(&base, "token".to_string()).unwrap();
1085
1086 let error = client
1087 .acquire(&test_lease_request())
1088 .await
1089 .expect_err("403 must terminate the receiver");
1090
1091 assert_eq!(attempts.load(Ordering::SeqCst), 1);
1092 assert_eq!(error.code, "COMMAND_RECEIVER_REQUEST_REJECTED");
1093 assert!(!error.retryable);
1094 assert!(!serde_json::to_string(&error)
1095 .unwrap()
1096 .contains("sensitive-provider-error-body"));
1097 server.abort();
1098 }
1099
1100 #[tokio::test]
1101 async fn transient_lease_rejection_remains_retryable() {
1102 let attempts = Arc::new(AtomicUsize::new(0));
1103 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1104 let address = listener.local_addr().unwrap();
1105 let server_attempts = attempts.clone();
1106 let server = tokio::spawn(async move {
1107 axum::serve(
1108 listener,
1109 Router::new()
1110 .route("/commands/leases", post(reject_lease_transiently))
1111 .with_state(server_attempts),
1112 )
1113 .await
1114 .unwrap();
1115 });
1116 let base = reqwest::Url::parse(&format!("http://{address}")).unwrap();
1117 let client = LeaseClient::from_base(&base, "token".to_string()).unwrap();
1118
1119 let error = client
1120 .acquire(&test_lease_request())
1121 .await
1122 .expect_err("503 must be retryable");
1123
1124 assert_eq!(attempts.load(Ordering::SeqCst), 1);
1125 assert_eq!(error.code, "HTTP_OPERATION_FAILED");
1126 assert!(error.retryable);
1127 server.abort();
1128 }
1129
1130 #[test]
1131 fn test_parse_envelope_json() {
1132 let envelope = create_test_envelope();
1133 let envelope_json = serde_json::to_value(&envelope).unwrap();
1134
1135 let queue_message = QueueMessage {
1136 id: "msg_123".to_string(),
1137 payload: MessagePayload::Json(envelope_json),
1138 receipt_handle: "handle_123".to_string(),
1139 timestamp: Utc::now(),
1140 source: "test-queue".to_string(),
1141 attributes: std::collections::HashMap::new(),
1142 attempt_count: Some(1),
1143 };
1144
1145 let parsed = parse_envelope(&queue_message).unwrap();
1146 assert!(parsed.is_some());
1147
1148 let parsed_envelope = parsed.unwrap();
1149 assert_eq!(parsed_envelope.command_id, "cmd_123");
1150 assert_eq!(parsed_envelope.command, "test-command");
1151 assert_eq!(parsed_envelope.protocol, PROTOCOL_VERSION);
1152 }
1153
1154 #[test]
1155 fn test_parse_envelope_text() {
1156 let envelope = create_test_envelope();
1157 let envelope_text = serde_json::to_string(&envelope).unwrap();
1158
1159 let queue_message = QueueMessage {
1160 id: "msg_456".to_string(),
1161 payload: MessagePayload::Text(envelope_text),
1162 receipt_handle: "handle_456".to_string(),
1163 timestamp: Utc::now(),
1164 source: "test-queue".to_string(),
1165 attributes: std::collections::HashMap::new(),
1166 attempt_count: Some(1),
1167 };
1168
1169 let parsed = parse_envelope(&queue_message).unwrap();
1170 assert!(parsed.is_some());
1171
1172 let parsed_envelope = parsed.unwrap();
1173 assert_eq!(parsed_envelope.command_id, "cmd_123");
1174 }
1175
1176 #[test]
1177 fn test_parse_non_command_message() {
1178 let queue_message = QueueMessage {
1179 id: "msg_789".to_string(),
1180 payload: MessagePayload::Json(serde_json::json!({"regular": "message"})),
1181 receipt_handle: "handle_789".to_string(),
1182 timestamp: Utc::now(),
1183 source: "test-queue".to_string(),
1184 attributes: std::collections::HashMap::new(),
1185 attempt_count: Some(1),
1186 };
1187
1188 let parsed = parse_envelope(&queue_message).unwrap();
1189 assert!(parsed.is_none());
1190 }
1191
1192 #[test]
1193 fn test_parse_invalid_protocol() {
1194 let mut envelope = create_test_envelope();
1195 envelope.protocol = "invalid.v1".to_string();
1196
1197 let envelope_json = serde_json::to_value(&envelope).unwrap();
1198 let queue_message = QueueMessage {
1199 id: "msg_invalid".to_string(),
1200 payload: MessagePayload::Json(envelope_json),
1201 receipt_handle: "handle_invalid".to_string(),
1202 timestamp: Utc::now(),
1203 source: "test-queue".to_string(),
1204 attributes: std::collections::HashMap::new(),
1205 attempt_count: Some(1),
1206 };
1207
1208 let parsed = parse_envelope(&queue_message).unwrap();
1209 assert!(parsed.is_none());
1210 }
1211
1212 #[test]
1213 fn test_create_test_response() {
1214 let response = create_test_response(b"Hello World");
1215 assert!(response.is_success());
1216
1217 if let CommandResponse::Success { response: body } = response {
1218 assert_eq!(body.decode_inline().unwrap(), b"Hello World");
1219 } else {
1220 panic!("Expected success response");
1221 }
1222 }
1223
1224 #[test]
1225 fn test_create_test_error() {
1226 let response = create_test_error("TEST_ERROR", "Something went wrong");
1227 assert!(response.is_error());
1228
1229 if let CommandResponse::Error { code, message, .. } = response {
1230 assert_eq!(code, "TEST_ERROR");
1231 assert_eq!(message, "Something went wrong");
1232 } else {
1233 panic!("Expected error response");
1234 }
1235 }
1236
1237 #[tokio::test]
1238 async fn test_decode_params_inline() {
1239 let params_json = serde_json::json!({"key": "value", "num": 42});
1240 let params_bytes = serde_json::to_vec(¶ms_json).unwrap();
1241
1242 let envelope = Envelope {
1243 protocol: PROTOCOL_VERSION.to_string(),
1244 target: crate::types::CommandTarget::new(
1245 "test-worker",
1246 crate::types::CommandTargetType::Worker,
1247 ),
1248 command_id: "cmd_decode".to_string(),
1249 attempt: 1,
1250 trace_context: None,
1251 deadline: None,
1252 command: "test".to_string(),
1253 params: BodySpec::inline(¶ms_bytes),
1254 response_handling: crate::types::ResponseHandling {
1255 max_inline_bytes: 150000,
1256 submit_response_url: "https://commands.example.com/response".to_string(),
1257 storage_upload_request: PresignedRequest::new_http(
1258 "https://storage.example.com/upload".to_string(),
1259 "PUT".to_string(),
1260 std::collections::HashMap::new(),
1261 PresignedOperation::Put,
1262 "test-path".to_string(),
1263 Utc::now() + chrono::Duration::hours(1),
1264 ),
1265 },
1266 deployment_id: "dep_123".to_string(),
1267 };
1268
1269 let decoded = decode_params(&envelope).await.unwrap();
1270 assert_eq!(decoded["key"], "value");
1271 assert_eq!(decoded["num"], 42);
1272 }
1273}