1use crate::{
4 percent_encode_path_segment, ActivityCall, AvroValue, Client, Error, HandlerKind, HistoryEvent,
5 RequestProtocol, Result,
6};
7use serde::{Deserialize, Serialize};
8use serde_json::{json, Value};
9use std::sync::{Arc, Mutex};
10use std::time::{Duration, Instant};
11
12#[derive(Debug, Default)]
13struct SessionState {
14 expires: Option<Instant>,
15 receipt: Option<Value>,
16 close_receipt: Option<Value>,
17 original_ttl: Option<(i64, u32)>,
18}
19
20#[derive(Clone, Debug)]
26pub struct WorkerSession {
27 client: Client,
28 worker_id: String,
29 options: WorkerSessionOptions,
30 state: Arc<Mutex<SessionState>>,
31 operation: Arc<tokio::sync::Mutex<()>>,
32}
33
34impl WorkerSession {
35 fn new(client: Client, worker_id: String, options: WorkerSessionOptions) -> Self {
36 Self {
37 client,
38 worker_id,
39 options,
40 state: Arc::new(Mutex::new(SessionState::default())),
41 operation: Arc::new(tokio::sync::Mutex::new(())),
42 }
43 }
44
45 pub fn options(&self) -> &WorkerSessionOptions {
46 &self.options
47 }
48
49 pub fn active(&self) -> bool {
50 self.state
51 .lock()
52 .ok()
53 .and_then(|state| state.expires)
54 .is_some_and(|expires| Instant::now() < expires)
55 }
56
57 pub fn snapshot(&self) -> Result<Option<Value>> {
59 Ok(self
60 .state
61 .lock()
62 .map_err(|_| Error::WorkflowStatePoisoned)?
63 .receipt
64 .clone())
65 }
66
67 pub async fn create(&self) -> Result<Value> {
68 let _operation = self.operation.lock().await;
69 if self
70 .state
71 .lock()
72 .map_err(|_| Error::WorkflowStatePoisoned)?
73 .close_receipt
74 .is_some()
75 {
76 return Err(invalid("a closed session identity cannot be recreated"));
77 }
78 let response = self
79 .client
80 .create_worker_session(&self.worker_id, &self.options)
81 .await;
82 let response = self.settle(response, &["created", "reused", "reacquired"])?;
83 Ok(response)
84 }
85
86 pub async fn renew(&self) -> Result<Value> {
88 let _operation = self.operation.lock().await;
89 if !self.active() {
90 return Err(invalid(
91 "cannot renew an uncreated, expired or closed local handle",
92 ));
93 }
94 let response = self
95 .client
96 .renew_worker_session(
97 &self.worker_id,
98 self.options.session_id(),
99 self.options.lease_seconds,
100 )
101 .await;
102 let response = self.settle(response, &["heartbeat_recorded"])?;
103 Ok(response)
104 }
105
106 pub async fn close(&self, reason: &str) -> Result<Value> {
108 let _operation = self.operation.lock().await;
109 if let Some(receipt) = self
110 .state
111 .lock()
112 .map_err(|_| Error::WorkflowStatePoisoned)?
113 .close_receipt
114 .clone()
115 {
116 return Ok(receipt);
117 }
118 self.invalidate()?;
119 let response = self
120 .client
121 .close_worker_session(&self.worker_id, self.options.session_id(), reason)
122 .await?;
123 self.validate_receipt(&response, &["closed", "already_closed"], "closed")?;
124 let mut state = self
125 .state
126 .lock()
127 .map_err(|_| Error::WorkflowStatePoisoned)?;
128 state.receipt = Some(response["session"].clone());
129 state.close_receipt = Some(response.clone());
130 Ok(response)
131 }
132
133 fn invalidate(&self) -> Result<()> {
134 self.state
135 .lock()
136 .map_err(|_| Error::WorkflowStatePoisoned)?
137 .expires = None;
138 Ok(())
139 }
140
141 fn validate_receipt(&self, receipt: &Value, outcomes: &[&str], status: &str) -> Result<()> {
142 let session = &receipt["session"];
143 if receipt["admitted"] != true
144 || !receipt["outcome"]
145 .as_str()
146 .is_some_and(|outcome| outcomes.contains(&outcome))
147 || session["session_id"].as_str() != Some(self.options.session_id())
148 || session["namespace"].as_str() != Some(self.client.namespace.as_str())
149 || session["lease_owner"].as_str() != Some(self.worker_id.as_str())
150 || session["status"].as_str() != Some(status)
151 {
152 return Err(invalid(
153 "Server did not acknowledge this session, namespace, holder and lifecycle outcome",
154 ));
155 }
156 Ok(())
157 }
158
159 fn accept(&self, receipt: &Value, outcomes: &[&str]) -> Result<()> {
160 self.validate_receipt(receipt, outcomes, "active")?;
161 self.track(&receipt["session"])?;
162 Ok(())
163 }
164
165 fn settle(&self, result: Result<Value>, outcomes: &[&str]) -> Result<Value> {
166 match result.and_then(|receipt| {
167 self.accept(&receipt, outcomes)?;
168 Ok(receipt)
169 }) {
170 Ok(receipt) => Ok(receipt),
171 Err(error) => {
172 self.invalidate()?;
173 Err(error)
174 }
175 }
176 }
177
178 pub(super) async fn wait_until_unavailable(&self) {
179 while self.active() {
180 let delay = self
181 .state
182 .lock()
183 .ok()
184 .and_then(|state| state.expires)
185 .map(|expires| expires.saturating_duration_since(Instant::now()))
186 .unwrap_or_default()
187 .min(Duration::from_millis(100));
188 tokio::time::sleep(delay).await;
189 }
190 }
191
192 pub(super) fn track(&self, affinity: &Value) -> Result<()> {
193 let received: WorkerSessionOptions = serde_json::from_value(affinity.clone())?;
194 if affinity["session_id"].as_str() != Some(self.options.session_id())
195 || affinity["status"] != "active"
196 || affinity["lease_owner"].as_str() != Some(self.worker_id.as_str())
197 || affinity["queue"].as_str() != self.options.queue.as_deref()
198 || received.to_wire()? != self.options.to_wire()?
199 || affinity
200 .get("namespace")
201 .is_some_and(|namespace| namespace.as_str() != Some(self.client.namespace.as_str()))
202 {
203 return Err(invalid(
204 "activity session affinity does not match the current holder and queue",
205 ));
206 }
207 let expires = lease_deadline(affinity)?;
208 let ttl =
209 chrono::DateTime::parse_from_rfc3339(affinity["ttl_expires_at"].as_str().unwrap())
210 .map_err(|_| invalid("invalid session TTL deadline"))?;
211 let ttl = (ttl.timestamp(), ttl.timestamp_subsec_nanos());
212 let mut state = self
213 .state
214 .lock()
215 .map_err(|_| Error::WorkflowStatePoisoned)?;
216 if state.original_ttl.is_some_and(|original| original != ttl) {
217 return Err(invalid("session renewal changed its original TTL deadline"));
218 }
219 state.original_ttl = Some(ttl);
220 state.expires = Some(expires);
221 state.receipt = Some(affinity.clone());
222 if let Some(receipt) = &mut state.receipt {
223 receipt["namespace"] = json!(self.client.namespace);
224 }
225 state.close_receipt = None;
226 Ok(())
227 }
228}
229
230fn lease_deadline(affinity: &Value) -> Result<Instant> {
231 let now = std::time::SystemTime::now();
232 let mut budget = Duration::MAX;
233 for field in ["lease_expires_at", "ttl_expires_at"] {
234 let deadline = affinity[field]
235 .as_str()
236 .and_then(|value| chrono::DateTime::parse_from_rfc3339(value).ok())
237 .ok_or_else(|| invalid("session receipt requires valid lease and TTL deadlines"))?;
238 let timestamp = deadline.timestamp();
239 if timestamp < 0 {
240 return Err(invalid("session lease or TTL already expired"));
241 }
242 let deadline = std::time::UNIX_EPOCH
243 + Duration::new(timestamp as u64, deadline.timestamp_subsec_nanos());
244 let remaining = deadline
245 .duration_since(now)
246 .map_err(|_| invalid("session lease or TTL already expired"))?;
247 if remaining.is_zero() {
248 return Err(invalid("session lease or TTL already expired"));
249 }
250 budget = budget.min(remaining);
251 }
252 Instant::now()
253 .checked_add(budget)
254 .ok_or_else(|| invalid("session deadline exceeds local clock range"))
255}
256
257#[derive(Clone, Debug, Deserialize)]
258pub(super) struct SessionActivityTask {
259 #[serde(flatten)]
260 pub(super) task: crate::ActivityTask,
261 #[serde(
262 default,
263 deserialize_with = "crate::activity_retry::deserialize_policy"
264 )]
265 pub(super) retry_policy: Option<Value>,
266 #[serde(default)]
267 pub(super) worker_session: Option<Value>,
268 #[serde(skip)]
269 pub(super) hydration_claim: Option<crate::activity_hydration::HydrationClaim>,
270 #[serde(skip)]
271 pub(super) activity_lease: Option<Arc<crate::activity_lease::authority::Lease>>,
272 #[serde(skip)]
273 pub(super) heartbeat_resume: crate::activity_checkpoint::HeartbeatResume,
274 #[serde(skip)]
277 pub(super) lease_deadline: Option<tokio::time::Instant>,
278}
279
280pub(super) struct ActivityInvocation {
281 pub(super) worker_session: Option<WorkerSession>,
282 pub(super) hydration_claim: Option<crate::activity_hydration::HydrationClaim>,
283 pub(super) retry_info: crate::ActivityRetryInfo,
284 pub(super) heartbeat_resume: crate::activity_checkpoint::HeartbeatResume,
285}
286
287#[cfg(test)]
288impl ActivityInvocation {
289 pub(super) fn unknown(attempt_number: u64) -> Self {
290 Self {
291 worker_session: None,
292 hydration_claim: None,
293 retry_info: crate::ActivityRetryInfo::new(attempt_number, None),
294 heartbeat_resume: Default::default(),
295 }
296 }
297}
298
299impl SessionActivityTask {
300 pub(super) fn invocation(&self, worker_session: Option<WorkerSession>) -> ActivityInvocation {
301 ActivityInvocation {
302 worker_session,
303 hydration_claim: self.hydration_claim.clone(),
304 retry_info: crate::ActivityRetryInfo::new(
305 self.task.attempt_number,
306 self.retry_policy.clone(),
307 ),
308 heartbeat_resume: self.heartbeat_resume.clone(),
309 }
310 }
311}
312
313#[derive(Debug, Deserialize)]
314pub(super) struct SessionPollResponse {
315 #[serde(default)]
316 pub(super) task: Option<SessionActivityTask>,
317 #[serde(default)]
318 poll_status: Option<String>,
319 #[serde(default)]
320 reason: Option<String>,
321}
322
323impl SessionPollResponse {
324 pub(super) fn outcome(&self) -> crate::WorkerPollOutcome {
325 crate::worker_poll_outcome(
326 self.task.is_some(),
327 self.poll_status.as_deref(),
328 self.reason.as_deref(),
329 )
330 }
331
332 pub(super) fn ordinary(self) -> crate::PollActivityTaskResponse {
333 crate::PollActivityTaskResponse {
334 task: self.task.map(|task| task.task),
335 poll_status: self.poll_status,
336 reason: self.reason,
337 }
338 }
339}
340
341impl crate::Worker {
342 pub fn worker_sessions(mut self, enabled: bool) -> Self {
344 self.client.worker_sessions_enabled = enabled;
345 self.session_registration_confirmed = Arc::new(std::sync::atomic::AtomicBool::new(false));
346 self
347 }
348
349 pub fn max_concurrent_worker_sessions(mut self, count: usize) -> Self {
350 self.client.max_concurrent_worker_sessions = count.max(1);
351 self
352 }
353
354 pub fn capabilities<I, S>(mut self, capabilities: I) -> Self
356 where
357 I: IntoIterator<Item = S>,
358 S: Into<String>,
359 {
360 self.resource_capabilities = capabilities
361 .into_iter()
362 .map(|value| value.into().trim().to_owned())
363 .collect();
364 self.resource_capabilities.sort();
365 self.resource_capabilities.dedup();
366 self
367 }
368
369 pub fn worker_session(&self, mut options: WorkerSessionOptions) -> Result<WorkerSession> {
371 self.require_session_registration()?;
372 if options.queue.is_none() {
373 options.queue = Some(self.task_queue.clone());
374 }
375 options.to_wire()?;
376 if options.queue.as_deref() != Some(self.task_queue.as_str()) {
377 return Err(invalid("session queue must match this worker"));
378 }
379 let mut sessions = self
380 .sessions
381 .lock()
382 .map_err(|_| Error::WorkflowStatePoisoned)?;
383 if let Some(session) = sessions.get(options.session_id()) {
384 if session.options.to_wire()? != options.to_wire()? {
385 return Err(invalid("session identity already has different options"));
386 }
387 return Ok(session.clone());
388 }
389 sessions.retain(|_, session| {
390 session
391 .state
392 .lock()
393 .map(|state| {
394 state.close_receipt.is_none()
395 && (Arc::strong_count(&session.state) > 1
396 || state
397 .expires
398 .is_some_and(|expires| Instant::now() < expires))
399 })
400 .unwrap_or(true)
401 });
402 if sessions.len() >= self.client.max_concurrent_worker_sessions {
403 return Err(invalid("local worker session capacity exhausted"));
404 }
405 let session = WorkerSession::new(
406 self.client.with_activity_lease_authority(None),
407 self.worker_id.clone(),
408 options,
409 );
410 sessions.insert(session.options.session_id.clone(), session.clone());
411 Ok(session)
412 }
413
414 pub(super) fn require_session_registration(&self) -> Result<()> {
415 if !self.client.worker_sessions_enabled
416 || !self
417 .session_registration_confirmed
418 .load(std::sync::atomic::Ordering::SeqCst)
419 {
420 return Err(invalid(
421 "register a session-capable worker before acquiring session handles or tasks",
422 ));
423 }
424 Ok(())
425 }
426
427 pub(super) fn track_session_task(
428 &self,
429 affinity: Option<&Value>,
430 ) -> Result<Option<WorkerSession>> {
431 let Some(affinity) = affinity.filter(|value| !value.is_null()) else {
432 return Ok(None);
433 };
434 let options: WorkerSessionOptions = serde_json::from_value(affinity.clone())?;
435 let session = self.worker_session(options)?;
436 session.track(affinity)?;
437 if let Some(authority) = &self.client.activity_lease_authority {
438 authority.attach_session(Some(&session))?;
439 }
440 Ok(Some(session))
441 }
442
443 pub(super) fn session_available(&self) -> usize {
444 self.sessions
445 .lock()
446 .map(|sessions| {
447 self.client
448 .max_concurrent_worker_sessions
449 .saturating_sub(sessions.values().filter(|session| session.active()).count())
450 })
451 .unwrap_or(0)
452 }
453
454 pub(super) async fn close_worker_sessions(&self) -> Result<()> {
455 let sessions: Vec<_> = self
456 .sessions
457 .lock()
458 .map_err(|_| Error::WorkflowStatePoisoned)?
459 .values()
460 .cloned()
461 .collect();
462 let mut first_error = None;
463 for session in sessions {
464 if session.snapshot()?.is_some() {
466 if let Err(error) = session.close("worker_shutdown").await {
467 if first_error.is_none() {
468 first_error = Some(error);
469 }
470 }
471 }
472 }
473 first_error.map_or(Ok(()), Err)
474 }
475}
476
477impl crate::ActivityContext {
478 pub fn worker_session(&self) -> Option<&WorkerSession> {
480 self.worker_session.as_ref()
481 }
482}
483
484pub(super) fn settle_activity_heartbeat(
485 session: &WorkerSession,
486 result: Result<Value>,
487 task_id: &str,
488 attempt_id: &str,
489 owner: &str,
490) -> Result<crate::ActivityHeartbeatResponse> {
491 let result = result.and_then(|value| {
492 if value["task_id"].as_str() != Some(task_id)
493 || value["activity_attempt_id"].as_str() != Some(attempt_id)
494 || value["lease_owner"].as_str() != Some(owner)
495 || value["can_continue"] != true
496 || value["heartbeat_recorded"] != true
497 || value["cancel_requested"] != false
498 {
499 return Err(invalid(
500 "activity heartbeat did not acknowledge this claim and session",
501 ));
502 }
503 session.track(&value["worker_session"])?;
504 serde_json::from_value(value).map_err(Error::from)
505 });
506 result.map_err(|error| {
507 let _ = session.invalidate();
508 Error::ActivityExecutionAbandoned(error.to_string())
509 })
510}
511
512#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
518pub struct WorkerSessionOptions {
519 session_id: String,
520 #[serde(default, skip_serializing_if = "Option::is_none")]
521 connection: Option<String>,
522 #[serde(default, skip_serializing_if = "Option::is_none")]
523 queue: Option<String>,
524 #[serde(default)]
525 requirements: Vec<String>,
526 #[serde(default = "default_lease")]
527 lease_seconds: u64,
528 #[serde(default = "default_ttl")]
529 ttl_seconds: u64,
530 #[serde(default = "default_concurrency")]
531 max_concurrent_activities: usize,
532 #[serde(default = "default_true")]
533 create_if_missing: bool,
534 #[serde(default = "default_true")]
535 allow_reacquire_after_failure: bool,
536}
537
538fn default_lease() -> u64 {
539 120
540}
541fn default_ttl() -> u64 {
542 1800
543}
544fn default_concurrency() -> usize {
545 1
546}
547fn default_true() -> bool {
548 true
549}
550
551impl WorkerSessionOptions {
552 pub fn new(session_id: impl Into<String>) -> Self {
553 Self {
554 session_id: session_id.into().trim().to_owned(),
555 connection: None,
556 queue: None,
557 requirements: Vec::new(),
558 lease_seconds: default_lease(),
559 ttl_seconds: default_ttl(),
560 max_concurrent_activities: 1,
561 create_if_missing: true,
562 allow_reacquire_after_failure: true,
563 }
564 }
565
566 pub fn session_id(&self) -> &str {
567 &self.session_id
568 }
569 pub fn task_queue(&self) -> Option<&str> {
570 self.queue.as_deref()
571 }
572 pub fn lease_duration(&self) -> Duration {
573 Duration::from_secs(self.lease_seconds)
574 }
575 pub fn ttl_duration(&self) -> Duration {
576 Duration::from_secs(self.ttl_seconds)
577 }
578 pub fn connection(mut self, connection: impl Into<String>) -> Self {
579 self.connection = Some(connection.into().trim().to_owned());
580 self
581 }
582 pub fn queue(mut self, queue: impl Into<String>) -> Self {
583 self.queue = Some(queue.into().trim().to_owned());
584 self
585 }
586 pub fn requirements<I, S>(mut self, requirements: I) -> Self
587 where
588 I: IntoIterator<Item = S>,
589 S: Into<String>,
590 {
591 self.requirements = requirements
592 .into_iter()
593 .map(|value| value.into().trim().to_owned())
594 .collect();
595 self.requirements.sort();
596 self.requirements.dedup();
597 self
598 }
599 pub fn lease_seconds(mut self, seconds: u64) -> Self {
600 self.lease_seconds = seconds;
601 self
602 }
603 pub fn ttl_seconds(mut self, seconds: u64) -> Self {
604 self.ttl_seconds = seconds;
605 self
606 }
607 pub fn max_concurrent_activities(mut self, count: usize) -> Self {
608 self.max_concurrent_activities = count;
609 self
610 }
611 pub fn create_if_missing(mut self, enabled: bool) -> Self {
612 self.create_if_missing = enabled;
613 self
614 }
615 pub fn allow_reacquire_after_failure(mut self, enabled: bool) -> Self {
616 self.allow_reacquire_after_failure = enabled;
617 self
618 }
619
620 pub fn to_wire(&self) -> Result<Value> {
621 identifier("session_id", &self.session_id)?;
622 for (field, value) in [("connection", &self.connection), ("queue", &self.queue)] {
623 if let Some(value) = value {
624 identifier(field, value)?;
625 }
626 }
627 for requirement in &self.requirements {
628 identifier("requirements", requirement)?;
629 }
630 if self.lease_seconds == 0
631 || self.ttl_seconds == 0
632 || self.max_concurrent_activities == 0
633 || self.lease_seconds > i64::MAX as u64
634 || self.ttl_seconds > i64::MAX as u64
635 || self.max_concurrent_activities as u128 > i64::MAX as u128
636 {
637 return Err(invalid("lease, TTL and concurrency must be positive"));
638 }
639 let mut canonical = self.clone();
640 canonical.requirements.sort();
641 canonical.requirements.dedup();
642 Ok(serde_json::to_value(canonical)?)
643 }
644}
645
646fn invalid(message: &str) -> Error {
647 Error::WorkerLoop(format!("invalid_worker_session: {message}"))
648}
649
650fn identifier(field: &str, value: &str) -> Result<()> {
651 if value.trim().is_empty() || value.trim() != value || value.chars().count() > 255 {
652 return Err(invalid(&format!(
653 "{field} must be a canonical non-empty string of at most 255 characters"
654 )));
655 }
656 Ok(())
657}
658
659pub(super) fn validate_resource_capability(value: &str) -> Result<()> {
660 identifier("capabilities", value)?;
661 if value.starts_with("prepared_local_")
662 || value.starts_with("cancellation_scope")
663 || matches!(
664 value,
665 "local_activities"
666 | "worker_sessions"
667 | "sticky_execution"
668 | "cooperative_cancellation"
669 | "timeout_cleanup"
670 | crate::worker_payload::PROTECTED_SIGNAL_VALIDATION
671 )
672 {
673 return Err(invalid(
674 "built-in execution capabilities must use their explicit worker opt-in",
675 ));
676 }
677 Ok(())
678}
679
680impl Client {
681 pub async fn create_worker_session(
686 &self,
687 worker_id: &str,
688 options: &WorkerSessionOptions,
689 ) -> Result<Value> {
690 identifier("worker_id", worker_id)?;
691 let mut body = options.to_wire()?;
692 body["worker_id"] = json!(worker_id);
693 self.request_json(
694 reqwest::Method::POST,
695 "/worker/sessions",
696 RequestProtocol::DefaultWorker,
697 Some(&body),
698 )
699 .await
700 }
701
702 pub async fn renew_worker_session(
704 &self,
705 worker_id: &str,
706 session_id: &str,
707 lease_seconds: u64,
708 ) -> Result<Value> {
709 identifier("worker_id", worker_id)?;
710 identifier("session_id", session_id)?;
711 if lease_seconds == 0 || lease_seconds > i64::MAX as u64 {
712 return Err(invalid(
713 "lease_seconds must be a positive signed 64-bit integer",
714 ));
715 }
716 self.request_json(
717 reqwest::Method::POST,
718 &format!(
719 "/worker/sessions/{}/heartbeat",
720 percent_encode_path_segment(session_id)
721 ),
722 RequestProtocol::DefaultWorker,
723 Some(&json!({"worker_id":worker_id,"lease_seconds":lease_seconds})),
724 )
725 .await
726 }
727
728 pub async fn close_worker_session(
730 &self,
731 worker_id: &str,
732 session_id: &str,
733 reason: &str,
734 ) -> Result<Value> {
735 identifier("worker_id", worker_id)?;
736 identifier("session_id", session_id)?;
737 self.request_json(
738 reqwest::Method::DELETE,
739 &format!(
740 "/worker/sessions/{}",
741 percent_encode_path_segment(session_id)
742 ),
743 RequestProtocol::DefaultWorker,
744 Some(&json!({"worker_id":worker_id,"reason":reason})),
745 )
746 .await
747 }
748}
749
750impl ActivityCall {
751 pub fn in_worker_session(mut self, options: WorkerSessionOptions) -> Self {
756 self.worker_session = Some(options);
757 self
758 }
759
760 pub async fn typed<O: serde::de::DeserializeOwned>(mut self) -> Result<O> {
762 let activity_type = self.activity_type.clone();
763 let result =
764 std::future::poll_fn(|cx| std::pin::Pin::new(&mut self).poll_avro_value(cx)).await?;
765 crate::decode_handler_result(result, HandlerKind::Activity, &activity_type)
766 }
767
768 pub async fn avro_value(mut self) -> Result<AvroValue> {
770 std::future::poll_fn(|cx| std::pin::Pin::new(&mut self).poll_avro_value(cx)).await
771 }
772}
773
774impl crate::ParallelCall {
775 pub fn in_worker_session(mut self, options: WorkerSessionOptions) -> Self {
777 self.worker_session = Some(options);
778 self
779 }
780}
781
782pub(super) fn recorded_session(events: &[&HistoryEvent], sequence: u64) -> Result<Option<Value>> {
783 let mut original = None;
784 for event in events {
785 for source in [Some(&event.payload), event.payload.get("activity")]
786 .into_iter()
787 .flatten()
788 {
789 let Some(value) = source.get("worker_session") else {
790 continue;
791 };
792 let session = if value.is_null() {
793 None
794 } else {
795 let mut value = value.clone();
796 if let Some(object) = value.as_object_mut() {
797 for field in ["lease_seconds", "ttl_seconds", "max_concurrent_activities"] {
798 if object.get(field).is_some_and(Value::is_null) {
799 object.remove(field);
800 }
801 }
802 }
803 let options = serde_json::from_value::<WorkerSessionOptions>(value)
804 .and_then(|options| options.to_wire().map_err(serde::de::Error::custom))
805 .map_err(|error| {
806 crate::invalid_recorded_history(
807 "worker_session_invalid",
808 sequence,
809 "valid worker-session routing",
810 &error.to_string(),
811 "recorded worker-session metadata is invalid",
812 )
813 })?;
814 Some(options)
815 };
816 if original.as_ref().is_some_and(|old| old != &session) {
817 return Err(crate::invalid_recorded_history(
818 "worker_session_conflict",
819 sequence,
820 "one worker-session identity",
821 "conflicting session options",
822 "activity history changes worker-session routing at one command boundary",
823 ));
824 }
825 original = Some(session);
826 }
827 }
828 Ok(original.flatten())
829}
830
831#[cfg(test)]
832mod tests {
833 use super::*;
834
835 #[test]
836 fn invalid_routing_and_lifetime_are_refused_before_dispatch() {
837 for options in [
838 WorkerSessionOptions::new(" "),
839 WorkerSessionOptions::new("render").queue(" "),
840 WorkerSessionOptions::new("render").connection(""),
841 WorkerSessionOptions::new("render").requirements([""]),
842 WorkerSessionOptions::new("render").lease_seconds(0),
843 WorkerSessionOptions::new("render").ttl_seconds(0),
844 WorkerSessionOptions::new("render").max_concurrent_activities(0),
845 ] {
846 assert!(
847 matches!(options.to_wire(), Err(Error::WorkerLoop(message)) if message.starts_with("invalid_worker_session:"))
848 );
849 }
850 }
851
852 #[test]
853 fn session_requirements_have_one_canonical_wire_identity() {
854 let a =
855 WorkerSessionOptions::new(" render ").requirements(["gpu:l4", "codec:av1", "gpu:l4"]);
856 let b = WorkerSessionOptions::new("render").requirements(["codec:av1", "gpu:l4"]);
857 assert_eq!(a, b);
858 assert_eq!(a.to_wire().unwrap(), b.to_wire().unwrap());
859 assert_eq!(
860 a.to_wire().unwrap()["requirements"],
861 json!(["codec:av1", "gpu:l4"])
862 );
863 }
864}