durable-workflow 4.10.1

Rust client and worker SDK for Durable Workflow Cloud and self-hosted Server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
//! One activity's original identity and acknowledged runtime authority.

use super::MAX_REQUEST_WINDOW;
use crate::{
    percent_encode_path_segment, wait_for_worker_stop, Client, Error, Result, WorkerSession,
};
use chrono::{DateTime, FixedOffset, SecondsFormat};
use serde_json::{json, Value};
use std::future::Future;
use std::sync::{
    atomic::{AtomicBool, Ordering},
    Arc, Mutex,
};
use std::time::Duration;
use tokio::sync::{oneshot, Notify};
use tokio::time::Instant as Clock;

mod session;

type Timestamp = DateTime<FixedOffset>;

fn lost(message: &str) -> Error {
    Error::ActivityExecutionAbandoned(format!("activity lease: {message}"))
}

fn timestamp(value: &Value) -> Result<Timestamp> {
    let text = value
        .as_str()
        .ok_or_else(|| lost("missing original UTC6 timing"))?;
    let date =
        DateTime::parse_from_rfc3339(text).map_err(|_| lost("invalid original UTC6 timing"))?;
    if date.to_rfc3339_opts(SecondsFormat::Micros, true) != text {
        return Err(lost(
            "original timing must be UTC with six fractional digits",
        ));
    }
    Ok(date)
}

fn duration(later: Timestamp, earlier: Timestamp) -> Result<Duration> {
    let value = (later - earlier)
        .to_std()
        .map_err(|_| lost("expired timing"))?;
    if value.is_zero() {
        return Err(lost("expired timing"));
    }
    Ok(value)
}

fn until(start: Clock, later: Timestamp, earlier: Timestamp) -> Result<Clock> {
    start
        .checked_add(duration(later, earlier)?)
        .ok_or_else(|| lost("timing exceeds the local clock"))
}

fn interval(seconds: i64) -> Result<chrono::TimeDelta> {
    chrono::TimeDelta::try_seconds(seconds)
        .ok_or_else(|| lost("heartbeat interval is out of range"))
}

#[derive(Debug)]
struct State {
    captured: Clock,
    lease_until: Clock,
    business_until: Option<Clock>,
    business_deadline: Option<Timestamp>,
    heartbeat_until: Option<Clock>,
    heartbeat_interval: Option<i64>,
    heartbeat_time: Option<Timestamp>,
    heartbeat_deadline: Option<Timestamp>,
    server_time: Timestamp,
    lease_expiry: Timestamp,
    last_renewal: Option<(Timestamp, Timestamp, Clock)>,
    session: Option<session::Session>,
}

impl State {
    fn remaining(&self) -> Result<Duration> {
        let bound = self
            .business_until
            .into_iter()
            .chain(self.heartbeat_until)
            .chain(self.session.as_ref().map(session::Session::bound))
            .fold(self.lease_until, Clock::min);
        bound
            .checked_duration_since(Clock::now())
            .filter(|value| !value.is_zero())
            .ok_or_else(|| lost("original execution budget expired"))
    }

    fn heartbeat_terms(
        task: &Value,
        deadlines: &Value,
        server: Timestamp,
    ) -> Result<(Option<Timestamp>, Option<i64>)> {
        let bound = deadlines
            .get("heartbeat")
            .filter(|value| !value.is_null())
            .map(timestamp)
            .transpose()?;
        let interval = task["retry_policy"]["heartbeat_timeout"]
            .as_i64()
            .filter(|value| *value > 0);
        if let Some(bound) = bound {
            let interval = interval.ok_or_else(|| lost("missing recorded heartbeat interval"))?;
            if bound - server > self::interval(interval)? {
                return Err(lost("heartbeat bound exceeds its recorded interval"));
            }
        }
        Ok((bound, interval))
    }

    fn delivery(task: &Value, server_time: &Value, worker: &str, namespace: &str) -> Result<Self> {
        let captured = Clock::now();
        let server_time = timestamp(server_time)?;
        let lease_expiry = timestamp(&task["lease_expires_at"])?;
        if duration(lease_expiry, server_time)? > Duration::from_secs(86_400) {
            return Err(lost("invalid original lease duration"));
        }
        let empty = json!({});
        let deadlines = task.get("deadlines").unwrap_or(&empty);
        if !deadlines.is_object() {
            return Err(lost("invalid original deadline map"));
        }
        let mut business_deadline = None;
        for name in ["start_to_close", "schedule_to_close", "run", "execution"] {
            if let Some(value) = deadlines.get(name).filter(|value| !value.is_null()) {
                let bound = timestamp(value)?;
                business_deadline = Some(
                    business_deadline.map_or(bound, |original: Timestamp| original.min(bound)),
                );
            }
        }
        let (heartbeat_deadline, heartbeat_interval) =
            Self::heartbeat_terms(task, deadlines, server_time)?;
        let state = Self {
            captured,
            lease_until: until(captured, lease_expiry, server_time)?,
            business_until: business_deadline
                .map(|bound| until(captured, bound, server_time))
                .transpose()?,
            business_deadline,
            heartbeat_until: heartbeat_deadline
                .map(|bound| until(captured, bound, server_time))
                .transpose()?,
            heartbeat_time: heartbeat_deadline
                .zip(heartbeat_interval)
                .map(|(bound, seconds)| {
                    bound
                        .checked_sub_signed(interval(seconds)?)
                        .ok_or_else(|| lost("heartbeat timing underflow"))
                })
                .transpose()?,
            heartbeat_interval,
            heartbeat_deadline,
            server_time,
            lease_expiry,
            last_renewal: None,
            session: session::Session::delivery(task, server_time, captured, worker, namespace)?,
        };
        state.remaining()?;
        Ok(state)
    }

    fn observe_progress(&mut self, reply: &Value, server: Timestamp, started: Clock) -> Result<()> {
        let Some(interval) = self.heartbeat_interval else {
            return Ok(());
        };
        let Ok(progress) = timestamp(&reply["last_heartbeat_at"]) else {
            return Ok(());
        };
        let Ok(deadline) = timestamp(&reply["heartbeat_deadline_at"]) else {
            return Ok(());
        };
        if progress > server
            || deadline <= server
            || deadline - progress != self::interval(interval)?
            || self
                .heartbeat_time
                .is_some_and(|previous| progress <= previous)
            || self
                .heartbeat_deadline
                .is_some_and(|previous| deadline <= previous)
        {
            return Ok(());
        }
        let bound = until(started, deadline, server)?;
        if bound > Clock::now() {
            self.heartbeat_until = Some(self.heartbeat_until.map_or(bound, |old| old.max(bound)));
            self.heartbeat_time = Some(progress);
            self.heartbeat_deadline = Some(deadline);
        }
        Ok(())
    }

    fn renewal(&mut self, reply: &Value, started: Clock) -> Result<()> {
        self.remaining()?;
        let server = timestamp(&reply["server_time"])?;
        let expiry = timestamp(&reply["lease_expires_at"])?;
        let grant = duration(expiry, server)?;
        let bound = until(started, expiry, server)?;
        if started < self.captured
            || started > Clock::now()
            || grant > Duration::from_secs(86_400)
            || bound <= Clock::now()
        {
            return Err(lost("invalid or consumed renewal grant"));
        }
        if self
            .heartbeat_time
            .is_some_and(|progress| server < progress)
            && expiry <= self.lease_expiry
        {
            return Ok(());
        }
        if server < self.server_time || expiry < self.lease_expiry {
            return Err(lost("renewal predates the acknowledged grant"));
        }
        if let Some(previous) = self.last_renewal {
            if server <= previous.0 {
                return if previous == (server, expiry, started) {
                    Ok(())
                } else {
                    Err(lost("replayed renewal"))
                };
            }
        }
        if let Some(deadline) = self.business_deadline {
            let observed = until(started, deadline, server)?;
            self.business_until = Some(
                self.business_until
                    .map_or(observed, |original| original.min(observed)),
            );
        }
        self.observe_progress(reply, server, started)?;
        if let Some(session) = &mut self.session {
            session.acknowledge(&reply["worker_session"], server, started)?;
        }
        self.lease_until = self.lease_until.max(bound);
        self.server_time = server;
        self.lease_expiry = expiry;
        self.last_renewal = Some((server, expiry, started));
        self.remaining().map(|_| ())
    }

    fn progress(&mut self, reply: &Value, started: Clock) -> Result<()> {
        self.remaining()?;
        if started < self.captured || started > Clock::now() {
            return Err(lost("invalid heartbeat clock"));
        }
        let progress = timestamp(&reply["last_heartbeat_at"])?;
        let expiry = timestamp(&reply["lease_expires_at"])?;
        let grant = duration(expiry, progress)?;
        if grant > Duration::from_secs(86_400) {
            return Err(lost("invalid heartbeat lease grant"));
        }
        if self.heartbeat_time.is_some_and(|old| progress <= old) {
            return Ok(());
        }
        let bound = until(started, expiry, progress)?;
        if bound <= Clock::now() {
            return Err(lost("heartbeat grant consumed in transport"));
        }
        if let Some(session) = &mut self.session {
            session.acknowledge(&reply["worker_session"], progress, started)?;
        }
        if let Some(interval) = self.heartbeat_interval {
            let deadline = progress
                .checked_add_signed(self::interval(interval)?)
                .ok_or_else(|| lost("heartbeat deadline overflow"))?;
            let heartbeat_until = until(started, deadline, progress)?;
            if heartbeat_until <= Clock::now() {
                return Err(lost("heartbeat progress consumed in transport"));
            }
            self.heartbeat_until = Some(
                self.heartbeat_until
                    .map_or(heartbeat_until, |old| old.max(heartbeat_until)),
            );
            self.heartbeat_deadline = Some(deadline);
        }
        self.heartbeat_time = Some(progress);
        self.lease_expiry = self.lease_expiry.max(expiry);
        self.lease_until = self.lease_until.max(bound);
        Ok(())
    }
}

#[derive(Debug)]
pub(crate) struct Authority {
    client: Client,
    task_id: String,
    attempt_id: String,
    owner: String,
    identity: Value,
    state: Mutex<State>,
    active: AtomicBool,
    changed: Notify,
}

impl Authority {
    fn delivery(client: &Client, wire: &Value, worker: &str, queue: &str) -> Result<Self> {
        let task = &wire["task"];
        for name in [
            "task_id",
            "workflow_id",
            "run_id",
            "activity_execution_id",
            "activity_attempt_id",
            "lease_owner",
            "task_queue",
        ] {
            if !task[name].as_str().is_some_and(|value| {
                !value.trim().is_empty() && value.trim() == value && value.chars().count() <= 255
            }) {
                return Err(lost("missing or malformed original activity identity"));
            }
        }
        if task["lease_owner"].as_str() != Some(worker)
            || task["task_queue"].as_str() != Some(queue)
            || task
                .get("namespace")
                .is_some_and(|value| value.as_str() != Some(client.namespace.as_str()))
            || !task["attempt_number"]
                .as_u64()
                .is_some_and(|value| value > 0)
            || task
                .get("attempt_id")
                .is_some_and(|alias| !alias.is_null() && *alias != task["activity_attempt_id"])
        {
            return Err(lost(
                "activity claim changed owner, queue, namespace or attempt",
            ));
        }
        let mut base = client.clone();
        base.activity_lease_authority = None;
        Ok(Self {
            client: base,
            task_id: task["task_id"].as_str().unwrap().to_owned(),
            attempt_id: task["activity_attempt_id"].as_str().unwrap().to_owned(),
            owner: worker.to_owned(),
            identity: json!({"workflow_task_id":task["task_id"],"workflow_instance_id":task["workflow_id"],
                "workflow_run_id":task["run_id"],"activity_execution_id":task["activity_execution_id"],
                "activity_attempt_id":task["activity_attempt_id"],"attempt_number":task["attempt_number"],"lease_owner":worker}),
            state: Mutex::new(State::delivery(
                task,
                &wire["server_time"],
                worker,
                &client.namespace,
            )?),
            active: AtomicBool::new(true),
            changed: Notify::new(),
        })
    }

    fn invalidate(&self, message: &str) -> Error {
        self.active.store(false, Ordering::SeqCst);
        self.changed.notify_waiters();
        lost(message)
    }

    fn remaining(&self) -> Result<Duration> {
        if !self.active.load(Ordering::SeqCst)
            || self
                .client
                .worker_storage_admission
                .as_ref()
                .is_some_and(|value| value.stop.load(Ordering::SeqCst))
        {
            return Err(self.invalidate("callback settled, claim lost or worker stopping"));
        }
        self.state
            .lock()
            .map_err(|_| lost("claim state poisoned"))?
            .remaining()
            .map_err(|error| self.invalidate(&error.to_string()))
    }

    pub(crate) fn attach_session(&self, handle: Option<&WorkerSession>) -> Result<()> {
        let mut state = self
            .state
            .lock()
            .map_err(|_| lost("claim state poisoned"))?;
        match (&mut state.session, handle) {
            (Some(session), Some(handle)) => session.attach(handle),
            (None, None) => Ok(()),
            _ => Err(self.invalidate("required session is unavailable")),
        }
    }

    pub(crate) fn refresh_delivery_session(&self, task: &mut Value) -> Result<()> {
        self.remaining()?;
        let state = self
            .state
            .lock()
            .map_err(|_| lost("claim state poisoned"))?;
        if let Some(session) = &state.session {
            task["worker_session"] = session.snapshot().clone();
        }
        Ok(())
    }

    pub(crate) fn governs(&self, path: &str) -> bool {
        (path.starts_with("/worker/activity-tasks/")
            && ["/complete", "/fail", "/heartbeat", "/renew-lease"]
                .iter()
                .any(|action| path.ends_with(action)))
            || path == "/external-payloads/v1"
    }

    pub(crate) fn check(&self, path: &str, body: Option<&Value>) -> Result<()> {
        if !self.governs(path) {
            return Ok(());
        }
        self.remaining()?;
        if path.starts_with("/worker/activity-tasks/") {
            let prefix = format!(
                "/worker/activity-tasks/{}/",
                percent_encode_path_segment(&self.task_id)
            );
            if !path.starts_with(&prefix)
                || body.is_none_or(|body| {
                    body["activity_attempt_id"].as_str() != Some(self.attempt_id.as_str())
                        || body["lease_owner"].as_str() != Some(self.owner.as_str())
                })
            {
                return Err(self.invalidate("publication changed its original claim identity"));
            }
        }
        Ok(())
    }

    pub(crate) async fn protect<T>(&self, operation: impl Future<Output = Result<T>>) -> Result<T> {
        tokio::pin!(operation);
        let stopped = async {
            match &self.client.worker_storage_admission {
                Some(admission) => wait_for_worker_stop(&admission.stop).await,
                None => std::future::pending::<()>().await,
            }
        };
        tokio::pin!(stopped);
        loop {
            let changed = self.changed.notified();
            tokio::pin!(changed);
            changed.as_mut().enable();
            let remaining = self.remaining()?;
            tokio::select! {
                biased;
                _ = &mut stopped => return Err(self.invalidate("worker stopping")),
                _ = tokio::time::sleep(remaining) => { self.remaining()?; },
                _ = &mut changed => { self.remaining()?; },
                value = &mut operation => { self.remaining()?; return value; },
            }
        }
    }

    pub(crate) fn progress(&self, reply: &Value, started: Clock) -> Result<()> {
        self.remaining()?;
        if reply["heartbeat_recorded"] != true
            || reply["can_continue"] != true
            || reply["cancel_requested"] != false
            || reply.get("reason").is_some_and(|value| !value.is_null())
            || reply["task_id"].as_str() != Some(self.task_id.as_str())
            || reply["activity_attempt_id"].as_str() != Some(self.attempt_id.as_str())
            || reply["lease_owner"].as_str() != Some(self.owner.as_str())
        {
            return Err(self.invalidate("heartbeat did not acknowledge this original activity"));
        }
        let result = self
            .state
            .lock()
            .map_err(|_| lost("claim state poisoned"))?
            .progress(reply, started);
        result.map_err(|error| self.invalidate(&error.to_string()))?;
        self.changed.notify_waiters();
        Ok(())
    }

    async fn renew(&self) -> Result<bool> {
        let started = Clock::now();
        let budget = self.remaining()?.min(MAX_REQUEST_WINDOW);
        let reply = self
            .client
            .renew_activity_task_lease(&self.task_id, &self.attempt_id, &self.owner, budget)
            .await;
        let reply = match reply {
            Ok(value) => value,
            Err(Error::Timeout | Error::Transport(_)) => {
                self.remaining()?;
                return Ok(false);
            }
            Err(Error::ActivityTaskRejected(ref rejection))
                if rejection.status >= 500 || rejection.status == 429 =>
            {
                self.remaining()?;
                return Ok(false);
            }
            Err(Error::Http { ref status, .. })
                if status.is_server_error() || status.as_u16() == 429 =>
            {
                self.remaining()?;
                return Ok(false);
            }
            Err(error) => return Err(self.invalidate(&error.to_string())),
        };
        self.remaining()?;
        if reply["lease_renewed"] != true
            || reply["can_continue"] != true
            || reply["cancel_requested"] != false
            || reply["heartbeat_recorded"] != false
            || reply.get("reason").is_some_and(|value| !value.is_null())
            || self
                .identity
                .as_object()
                .unwrap()
                .iter()
                .any(|(key, value)| reply.get(key) != Some(value))
        {
            return Err(self.invalidate("renewal changed the original identity or authority"));
        }
        let result = self
            .state
            .lock()
            .map_err(|_| lost("claim state poisoned"))?
            .renewal(&reply, started);
        result.map_err(|error| self.invalidate(&error.to_string()))?;
        self.changed.notify_waiters();
        Ok(true)
    }

    async fn maintain(&self) -> Result<()> {
        let mut confirmed = true;
        loop {
            let mut delay = (self.remaining()? / 3).min(if confirmed {
                Duration::from_secs(30)
            } else {
                Duration::from_secs(1)
            });
            if let Some(interval) = self
                .state
                .lock()
                .map_err(|_| lost("claim state poisoned"))?
                .heartbeat_interval
            {
                delay = delay.min(Duration::from_secs(interval as u64) / 3);
            }
            tokio::time::sleep(delay).await;
            confirmed = self.renew().await?;
        }
    }
}

#[derive(Debug)]
pub(crate) struct Lease {
    pub(crate) authority: Arc<Authority>,
    maintenance: tokio::task::JoinHandle<()>,
}

struct MaintenanceExit(Arc<Authority>);
impl Drop for MaintenanceExit {
    fn drop(&mut self) {
        self.0.invalidate("lease-maintenance task stopped");
    }
}

impl Lease {
    pub(crate) async fn confirm(
        client: &Client,
        wire: &Value,
        worker: &str,
        queue: &str,
    ) -> Result<Option<Arc<Self>>> {
        client.observe_activity_lease_capabilities(&wire["server_capabilities"]);
        if wire["task"].is_null()
            || !client
                .activity_lease_renewal_supported
                .load(Ordering::SeqCst)
        {
            return Ok(None);
        }
        let authority = Arc::new(Authority::delivery(client, wire, worker, queue)?);
        if !authority.renew().await? {
            return Err(authority.invalidate("initial lease confirmation unavailable"));
        }
        let maintained = Arc::clone(&authority);
        let (started_tx, started_rx) = oneshot::channel();
        let maintenance = tokio::spawn(async move {
            let _exit = MaintenanceExit(Arc::clone(&maintained));
            let _ = started_tx.send(());
            if let Err(error) = maintained.maintain().await {
                maintained.invalidate(&error.to_string());
            }
        });
        let lease = Arc::new(Self {
            authority,
            maintenance,
        });
        // Poll the maintainer before callback entry. A newly spawned task can
        // remain in Tokio's non-stealable LIFO slot while its spawning task
        // blocks, even when another executor thread is available.
        started_rx.await.map_err(|_| {
            lease
                .authority
                .invalidate("lease-maintenance task stopped before callback entry")
        })?;
        lease.authority.remaining()?;
        Ok(Some(lease))
    }
}

impl Drop for Lease {
    fn drop(&mut self) {
        self.authority
            .invalidate("activity claim settled or abandoned");
        self.maintenance.abort();
    }
}