laravel-rust-workflow 0.2.0

Internal crate of Laravel for Rust: durable workflows. Depend on `laravel-rust` instead
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
//! Advancing a run: claim its lease, replay `handle` until it returns or suspends, then save how
//! the advance ended and queue the next one.

use std::collections::HashMap;
use std::future::{Future, poll_fn};
use std::pin::pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::task::{Poll, Wake, Waker};
use std::time::Duration;

use futures_util::future::BoxFuture;
use jiff::Timestamp;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use tracing::Instrument;

use super::ErasedStore;
use super::events::{RunCancelled, RunCompleted, RunFailed};
use super::registration::__Registration;
use super::run::{Ending, Run};
use super::store::{Claim, Lease, Outcome, RunRecord};
use super::{Manager, RunId};
use crate::context::{Context, Internals};
use crate::errors::panic;
use crate::queue::{Attempt, Job, JobOptions, QueueManager, QueueManagerInternals as _};
use crate::{Error, Result};

/// How long an advance holds its run before another may take it, unless the advance renews it.
const LEASE: Duration = Duration::from_secs(60);

/// How long a wake-up waits before trying again when another advance holds the run.
const HELD_RETRY: Duration = Duration::from_secs(10);

/// How one advance of a run ended.
#[derive(Debug)]
pub enum Advanced {
    /// Another advance holds the run.
    Held,
    /// The run had already ended, or doesn't exist.
    Ended,
    /// The run suspended.
    Waiting {
        /// When it next has something to do, or `None` until a resume.
        wake_at: Option<Timestamp>,
        /// Whether the advance must queue the wake-up, because no earlier one is queued for it.
        schedule: bool,
        workflow: String,
        connection: String,
        queue: String,
    },
    /// The workflow returned.
    Completed,
    /// The run failed for good, with this error.
    Failed(Error),
    /// The advance lost its lease while advancing, because the run was cancelled or another
    /// worker claimed it.
    Lost,
}

/// Advance a run once.
///
/// `replacements` are step outputs, as JSON, that a test gives in place of running the steps.
///
/// # Errors
///
/// Returns an error if loading, claiming, executing, or persisting the workflow run fails.
pub async fn advance(id: RunId, replacements: HashMap<String, String>) -> Result<Advanced> {
    let context = Context::expect("a workflow advance");
    let store = Manager::of(context.services()).store()?;
    let (record, entries, lease) = match store.claim(id, LEASE).await? {
        Claim::Claimed { run, entries, lease } => (*run, entries, lease),
        Claim::Held => return Ok(Advanced::Held),
        Claim::Ended => return Ok(Advanced::Ended),
    };

    // Every advance runs with the context values the run was started with...
    let advancing = context.fresh();
    let (logged, hidden) = decode_context(&record.context);
    advancing.restore_values(logged, hidden);

    let span = tracing::info_span!(
        target: crate::foundation::telemetry::WORKFLOW_TARGET,
        "workflow",
        workflow.run = %id,
        workflow.name = %record.workflow,
        otel.name = %format_args!("workflow {}", record.workflow),
        otel.status_code = tracing::field::Empty,
    );
    let advanced = advancing
        .scope(advance_claimed(store, record, entries, lease, replacements))
        .instrument(span.clone())
        .await;
    if let Err(error) | Ok(Advanced::Failed(error)) = &advanced {
        crate::foundation::telemetry::fail(&span, error);
    }

    advanced
}

async fn advance_claimed(
    store: Arc<dyn ErasedStore>,
    record: RunRecord,
    entries: Vec<super::store::Entry>,
    lease: Lease,
    replacements: HashMap<String, String>,
) -> Result<Advanced> {
    let id = record.id;
    let registration = match __Registration::find(&record.workflow) {
        Ok(registration) => registration,
        Err(error) => return fail(&*store, &record, &lease, None, error).await,
    };
    let input: Value = match serde_json::from_str(&record.input) {
        Ok(input) => input,
        Err(error) => {
            let error = crate::error::fail(format!("the run's input isn't JSON: {error}"));
            return fail(&*store, &record, &lease, Some(registration), error).await;
        }
    };

    let run = Arc::new(Run::new(
        id,
        lease.clone(),
        registration.name(),
        record.created_at,
        Arc::clone(&store),
        entries,
        record.attributes.clone(),
        replacements,
    ));
    let handle = match registration.advance(input, Arc::clone(&run)).await {
        Ok(handle) => handle,
        Err(error) => return fail(&*store, &record, &lease, Some(registration), error).await,
    };

    let Some(driven) = renewing(&*store, id, &lease, drive(&run, handle)).await else {
        return Ok(Advanced::Lost);
    };
    let mut ending = run.state().ending.take();
    let now = now();
    let attributes = run.attributes();
    if attributes != record.attributes && !matches!(ending, Some(Ending::Store(_) | Ending::Lost)) {
        match store.set_attributes(id, &lease, attributes).await {
            Ok(true) => {}
            Ok(false) => ending = Some(Ending::Lost),
            Err(error) => ending = Some(Ending::Store(error)),
        }
    }
    match (ending, driven) {
        (Some(Ending::Store(error)), _) => {
            // Give up the lease, so the queue's retry of this advance can take the run...
            let _ = store
                .release(id, &lease, Outcome::Waiting { wake_at: Some(now) }, now)
                .await;

            Err(error)
        }
        (Some(Ending::Lost), _) => Ok(Advanced::Lost),
        (Some(Ending::Broken(error)), _) | (None, Driven::Returned(Err(error))) => {
            fail(&*store, &record, &lease, Some(registration), error).await
        }
        (None, Driven::Returned(Ok(output))) => {
            if !store.release(id, &lease, Outcome::Completed { output }, now).await? {
                return Ok(Advanced::Lost);
            }
            emit(RunCompleted {
                run_id: id,
                workflow: record.workflow.clone(),
            })
            .await;

            Ok(Advanced::Completed)
        }
        (None, Driven::Suspended(wake_at)) => {
            if !store.release(id, &lease, Outcome::Waiting { wake_at }, now).await? {
                return Ok(Advanced::Lost);
            }
            // A wake-up is already queued when an earlier advance suspended until the same time...
            let queued = record.wake_at == wake_at && record.wake_at.is_some_and(|previous| previous > now);

            Ok(Advanced::Waiting {
                wake_at,
                schedule: wake_at.is_some() && !queued,
                workflow: record.workflow,
                connection: record.connection,
                queue: record.queue,
            })
        }
        (None, Driven::Outside) => {
            let after = run.passed().map_or_else(
                || "before its first operation".to_owned(),
                |passed| format!("after the {passed}"),
            );
            let error = crate::error::fail(format!(
                "the workflow `{}` awaited something outside a step {after}: do I/O inside `run.step(..)`",
                record.workflow
            ));

            fail(&*store, &record, &lease, Some(registration), error).await
        }
    }
}

/// Fail the run for good, then run the workflow's `failed` hook and dispatch [`RunFailed`].
async fn fail(
    store: &dyn ErasedStore,
    record: &RunRecord,
    lease: &Lease,
    registration: Option<&__Registration>,
    error: Error,
) -> Result<Advanced> {
    let message = format!("{error:#}");
    if !store
        .release(record.id, lease, Outcome::Failed { error: message }, now())
        .await?
    {
        return Ok(Advanced::Lost);
    }

    let context = Context::expect("a workflow advance");
    context.report(error.clone());
    if let Some(registration) = registration {
        let input = serde_json::from_str(&record.input).unwrap_or(Value::Null);
        if let Err(error) = panic::catch(registration.failed(input, &error)).await {
            context.report(error);
        }
    }
    emit(RunFailed {
        run_id: record.id,
        workflow: record.workflow.clone(),
        error: error.clone(),
    })
    .await;

    Ok(Advanced::Failed(error))
}

/// Cancel a run and dispatch [`RunCancelled`], returning whether the run was cancelled.
pub(super) async fn cancel(context: &Context, id: RunId, reason: Option<String>) -> Result<bool> {
    let store = Manager::of(context.services()).store()?;
    if !store.cancel(id, reason.clone(), now()).await? {
        return Ok(false);
    }
    let workflow = store.find(id).await?.map(|run| run.workflow).unwrap_or_default();
    emit(RunCancelled {
        run_id: id,
        workflow,
        reason,
    })
    .await;

    Ok(true)
}

async fn emit<E: Send + Sync + 'static>(event: E) {
    if let Err(error) = panic::catch(crate::event::dispatch(event)).await {
        Context::expect("a workflow event").report(error);
    }
}

/// Run `future`, renewing the run's lease until it finishes or the lease is lost.
async fn renewing<F: Future>(store: &dyn ErasedStore, id: RunId, lease: &Lease, future: F) -> Option<F::Output> {
    let mut future = pin!(future);
    let period = LEASE / 3;
    let mut renewals = tokio::time::interval_at(tokio::time::Instant::now() + period, period);
    loop {
        tokio::select! {
            output = &mut future => return Some(output),
            _ = renewals.tick() => {
                match store.renew(id, lease, LEASE).await {
                    Ok(true) => {}
                    Ok(false) => return None,
                    Err(error) => Context::expect("a workflow advance").report(error),
                }
            }
        }
    }
}

/// How polling `handle` ended.
enum Driven {
    /// `handle` returned.
    Returned(Result<String>),
    /// Every operation `handle` waits on suspended the run.
    Suspended(Option<Timestamp>),
    /// `handle` waits on something that is neither an operation nor ready.
    Outside,
}

/// Poll `handle` until it returns, or until it is pending with no operation doing work. It has
/// then suspended, when an operation suspended the run, or it awaits something outside a step.
fn drive<'a>(run: &'a Run, mut handle: BoxFuture<'static, Result<String>>) -> impl Future<Output = Driven> + Send + 'a {
    poll_fn(move |cx| {
        loop {
            let flag = Arc::new(Flag {
                woken: AtomicBool::new(false),
                waker: cx.waker().clone(),
            });
            let waker = Waker::from(Arc::clone(&flag));
            if let Poll::Ready(output) = handle.as_mut().poll(&mut std::task::Context::from_waker(&waker)) {
                return Poll::Ready(Driven::Returned(output));
            }

            let state = run.state();
            if state.is_busy() {
                return Poll::Pending;
            }
            // A future that woke itself while it was polled, such as a yield, is polled again...
            if flag.woken.load(Ordering::Acquire) {
                continue;
            }

            return Poll::Ready(match state.suspension() {
                Some(wake_at) => Driven::Suspended(wake_at),
                None => Driven::Outside,
            });
        }
    })
}

/// A waker that notes whether it was woken, then wakes the executor's own.
struct Flag {
    woken: AtomicBool,
    waker: Waker,
}

impl Wake for Flag {
    fn wake(self: Arc<Self>) {
        self.wake_by_ref();
    }

    fn wake_by_ref(self: &Arc<Self>) {
        self.woken.store(true, Ordering::Release);
        self.waker.wake_by_ref();
    }
}

/// Queue an advance of the run, at `at` or straight away. On a connection that runs jobs as
/// they're sent, a later advance waits for the test or `workflow:recover`, since the connection
/// can't delay it.
pub(super) async fn schedule(
    id: RunId,
    workflow: &str,
    connection: &str,
    queue: &str,
    at: Option<Timestamp>,
) -> Result<()> {
    let context = Context::expect("a workflow wake-up");
    let due = at.filter(|at| *at > now());
    if due.is_some() && QueueManager::of(context.services()).runs_inline(connection)? {
        return Ok(());
    }

    let mut dispatch = crate::queue::dispatch(Advance { run_id: id })
        .on_connection(connection)
        .on_queue(queue)
        .display_name(format!("workflow {}", crate::console::theme::type_label(workflow)));
    if let Some(at) = due {
        dispatch = dispatch.delay(at);
    }
    dispatch.await?;

    Ok(())
}

/// The time on the application's clock, which runs keep their times by.
pub fn now() -> Timestamp {
    Timestamp::try_from(crate::clock::system_now()).unwrap_or(Timestamp::UNIX_EPOCH)
}

/// Encode the context values a run starts with, as its store keeps them.
///
/// # Errors
///
/// Returns an error if serializing the context values fails.
pub fn encode_context(context: &Context) -> Result<String> {
    let values = context.values();

    Ok(serde_json::to_string(&serde_json::json!({
        "logged": values.logged,
        "hidden": values.hidden(),
    }))?)
}

fn decode_context(context: &str) -> (Map<String, Value>, Map<String, Value>) {
    let mut values: Map<String, Value> = serde_json::from_str(context).unwrap_or_default();
    let mut take = |key: &str| match values.remove(key) {
        Some(Value::Object(map)) => map,
        _ => Map::new(),
    };

    (take("logged"), take("hidden"))
}

/// The queued job that advances a run once.
#[derive(Serialize, Deserialize)]
pub(super) struct Advance {
    pub(super) run_id: RunId,
}

crate::queue::__queueable::serde_queueable!(Advance);

impl Job for Advance {
    const NAME: &'static str = "laravel.workflow.advance.v1";

    fn options() -> JobOptions {
        // A step may run as long as its own timeout allows, and the lease keeps other advances out...
        JobOptions::new()
            .tries(10)
            .timeout(Duration::from_secs(60 * 60))
            .backoff([Duration::from_secs(1), Duration::from_secs(10), Duration::from_secs(60)])
    }

    async fn handle(self, attempt: &Attempt) -> Result<()> {
        match advance(self.run_id, HashMap::new()).await? {
            Advanced::Waiting {
                wake_at,
                schedule: true,
                workflow,
                connection,
                queue,
            } => schedule(self.run_id, &workflow, &connection, &queue, wake_at).await,
            Advanced::Held => {
                let store = Manager::of(Context::expect("a workflow advance").services()).store()?;
                let Some(run) = store.find(self.run_id).await? else {
                    return Ok(());
                };
                let at = Timestamp::try_from(crate::clock::system_now() + HELD_RETRY).ok();

                schedule(self.run_id, &run.workflow, &run.connection, &run.queue, at).await
            }
            // The run reported its failure, and `workflow:retry` retries it, so the queue mustn't...
            Advanced::Failed(error) => {
                attempt.fail_settled(error);
                Ok(())
            }
            _ => Ok(()),
        }
    }
}

inventory::submit! { crate::queue::__Registration::new::<Advance>() }