runledger-runtime 0.11.0

Async worker, scheduler, and reaper runtime for the Runledger job system
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
use std::any::Any;
use std::future::Future;
use std::panic::AssertUnwindSafe;
use std::sync::Arc;
use std::time::Duration;

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use futures_util::{FutureExt, StreamExt, stream::FuturesUnordered};
use runledger_core::jobs::{JobDeadLetterReason, JobFailure, JobTypeName};
use tracing::warn;
use uuid::Uuid;

#[cfg(test)]
const OBSERVER_TIMEOUT: Duration = Duration::from_millis(100);
#[cfg(not(test))]
const OBSERVER_TIMEOUT: Duration = Duration::from_secs(10);

#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ObservedJob {
    pub job_id: Uuid,
    pub job_type: JobTypeName,
    pub organization_id: Option<Uuid>,
    pub run_number: i32,
    pub attempt: i32,
    pub max_attempts: i32,
    pub worker_id: String,
}

impl ObservedJob {
    #[must_use]
    pub fn new(
        job_id: Uuid,
        job_type: JobTypeName,
        organization_id: Option<Uuid>,
        run_number: i32,
        attempt: i32,
        max_attempts: i32,
        worker_id: impl Into<String>,
    ) -> Self {
        Self {
            job_id,
            job_type,
            organization_id,
            run_number,
            attempt,
            max_attempts,
            worker_id: worker_id.into(),
        }
    }
}

#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct JobRunningEvent {
    pub job: ObservedJob,
}

impl JobRunningEvent {
    #[must_use]
    pub fn new(job: ObservedJob) -> Self {
        Self { job }
    }
}

#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct JobSucceededEvent {
    pub job: ObservedJob,
    pub duration: Duration,
    pub progress_done: Option<i64>,
    pub progress_total: Option<i64>,
}

impl JobSucceededEvent {
    #[must_use]
    pub fn new(
        job: ObservedJob,
        duration: Duration,
        progress_done: Option<i64>,
        progress_total: Option<i64>,
    ) -> Self {
        Self {
            job,
            duration,
            progress_done,
            progress_total,
        }
    }
}

#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct JobContinuedEvent {
    /// Identity of the successfully completed run slice.
    pub job: ObservedJob,
    pub duration: Duration,
    pub next_run_number: i32,
    pub next_run_at: DateTime<Utc>,
    pub progress_done: Option<i64>,
    pub progress_total: Option<i64>,
}

impl JobContinuedEvent {
    #[must_use]
    pub fn new(
        job: ObservedJob,
        duration: Duration,
        next_run_number: i32,
        next_run_at: DateTime<Utc>,
        progress_done: Option<i64>,
        progress_total: Option<i64>,
    ) -> Self {
        Self {
            job,
            duration,
            next_run_number,
            next_run_at,
            progress_done,
            progress_total,
        }
    }
}

/// The failure transition that was durably committed before observer delivery.
///
/// This is authoritative for the effective retry schedule. The timing retained
/// on [`JobFailedEvent::failure`] is the handler's request, which may be ignored
/// when the failure is dead-lettered.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum JobFailureDisposition {
    /// Another attempt was scheduled from a relative delay.
    RetryScheduled {
        /// Persisted positive delay, rounded up to millisecond precision.
        retry_delay_ms: i32,
        /// Effective claim time calculated from the PostgreSQL completion clock.
        next_run_at: DateTime<Utc>,
    },
    /// The handler's lower bound selected the effective retry schedule.
    RetryScheduledAt {
        /// Handler not-before time, rounded up to PostgreSQL microsecond
        /// precision.
        requested_retry_at: DateTime<Utc>,
        /// Effective claim time. This is never earlier than policy backoff.
        next_run_at: DateTime<Utc>,
    },
    /// No retry was scheduled and the job was dead-lettered.
    DeadLettered { reason: JobDeadLetterReason },
    /// A future persistence disposition unknown to this runtime version.
    Unknown,
}

#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct JobFailedEvent {
    pub job: ObservedJob,
    pub duration: Duration,
    /// Handler failure, including any requested retry timing.
    pub failure: JobFailure,
    /// Authoritative post-commit retry or dead-letter outcome.
    pub disposition: JobFailureDisposition,
}

impl JobFailedEvent {
    #[must_use]
    pub fn new(
        job: ObservedJob,
        duration: Duration,
        failure: JobFailure,
        disposition: JobFailureDisposition,
    ) -> Self {
        Self {
            job,
            duration,
            failure,
            disposition,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum JobCompletionPersistenceOperation {
    /// Terminal-success persistence failed.
    Success,
    /// Successful handler-continuation persistence failed.
    Continuation,
    /// Failure/retry/dead-letter persistence failed.
    Failure,
}

#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct JobCompletionPersistFailedEvent {
    pub job: ObservedJob,
    pub duration: Duration,
    pub operation: JobCompletionPersistenceOperation,
    pub error: String,
}

impl JobCompletionPersistFailedEvent {
    #[must_use]
    pub fn new(
        job: ObservedJob,
        duration: Duration,
        operation: JobCompletionPersistenceOperation,
        error: impl Into<String>,
    ) -> Self {
        Self {
            job,
            duration,
            operation,
            error: error.into(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum JobLeaseReapedDisposition {
    ReleasedToPending,
    RetryScheduled {
        retry_delay_ms: i32,
        next_run_at: DateTime<Utc>,
    },
    DeadLettered {
        reason: JobDeadLetterReason,
    },
    Unknown,
}

#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct JobLeaseLostEvent {
    pub job: ObservedJob,
    pub duration: Duration,
    pub failure: JobFailure,
}

impl JobLeaseLostEvent {
    #[must_use]
    pub fn new(job: ObservedJob, duration: Duration, failure: JobFailure) -> Self {
        Self {
            job,
            duration,
            failure,
        }
    }
}

#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct JobLeaseReapedEvent {
    pub job: ObservedJob,
    pub failure: JobFailure,
    pub started_without_renewal_heartbeat: bool,
    pub disposition: JobLeaseReapedDisposition,
}

impl JobLeaseReapedEvent {
    #[must_use]
    pub fn new(
        job: ObservedJob,
        failure: JobFailure,
        started_without_renewal_heartbeat: bool,
        disposition: JobLeaseReapedDisposition,
    ) -> Self {
        Self {
            job,
            failure,
            started_without_renewal_heartbeat,
            disposition,
        }
    }
}

#[async_trait]
pub trait JobLifecycleObserver: Send + Sync {
    async fn on_job_running(&self, _event: JobRunningEvent) {}

    async fn on_job_continued(&self, _event: JobContinuedEvent) {}

    async fn on_job_succeeded(&self, _event: JobSucceededEvent) {}

    async fn on_job_failed(&self, _event: JobFailedEvent) {}

    async fn on_job_completion_persist_failed(&self, _event: JobCompletionPersistFailedEvent) {}

    async fn on_job_lease_lost(&self, _event: JobLeaseLostEvent) {}

    async fn on_job_lease_reaped(&self, _event: JobLeaseReapedEvent) {}
}

#[derive(Clone, Default)]
pub struct JobLifecycleObservers {
    observers: Arc<Vec<Arc<dyn JobLifecycleObserver>>>,
}

impl JobLifecycleObservers {
    #[must_use]
    pub fn empty() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn from_observer(observer: impl JobLifecycleObserver + 'static) -> Self {
        Self {
            observers: Arc::new(vec![Arc::new(observer)]),
        }
    }

    #[must_use]
    pub fn from_arc_observers(observers: Vec<Arc<dyn JobLifecycleObserver>>) -> Self {
        Self {
            observers: Arc::new(observers),
        }
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.observers.is_empty()
    }

    pub(crate) async fn job_running(&self, event: JobRunningEvent) {
        let job = event.job.clone();
        self.notify_all_observers(
            "on_job_running",
            event,
            &job,
            |observer, event| async move {
                observer.on_job_running(event).await;
            },
        )
        .await;
    }

    pub(crate) async fn job_succeeded(&self, event: JobSucceededEvent) {
        let job = event.job.clone();
        self.notify_all_observers(
            "on_job_succeeded",
            event,
            &job,
            |observer, event| async move {
                observer.on_job_succeeded(event).await;
            },
        )
        .await;
    }

    pub(crate) async fn job_continued(&self, event: JobContinuedEvent) {
        let job = event.job.clone();
        self.notify_all_observers(
            "on_job_continued",
            event,
            &job,
            |observer, event| async move {
                observer.on_job_continued(event).await;
            },
        )
        .await;
    }

    pub(crate) async fn job_failed(&self, event: JobFailedEvent) {
        let job = event.job.clone();
        self.notify_all_observers("on_job_failed", event, &job, |observer, event| async move {
            observer.on_job_failed(event).await;
        })
        .await;
    }

    pub(crate) async fn job_completion_persist_failed(
        &self,
        event: JobCompletionPersistFailedEvent,
    ) {
        let job = event.job.clone();
        self.notify_all_observers(
            "on_job_completion_persist_failed",
            event,
            &job,
            |observer, event| async move {
                observer.on_job_completion_persist_failed(event).await;
            },
        )
        .await;
    }

    pub(crate) async fn job_lease_lost(&self, event: JobLeaseLostEvent) {
        let job = event.job.clone();
        self.notify_all_observers(
            "on_job_lease_lost",
            event,
            &job,
            |observer, event| async move {
                observer.on_job_lease_lost(event).await;
            },
        )
        .await;
    }

    pub(crate) async fn job_lease_reaped(&self, event: JobLeaseReapedEvent) {
        let job = event.job.clone();
        self.notify_all_observers(
            "on_job_lease_reaped",
            event,
            &job,
            |observer, event| async move {
                observer.on_job_lease_reaped(event).await;
            },
        )
        .await;
    }

    async fn notify_all_observers<E, F, Fut>(
        &self,
        callback_name: &'static str,
        event: E,
        job: &ObservedJob,
        notify: F,
    ) where
        E: Clone,
        F: Fn(Arc<dyn JobLifecycleObserver>, E) -> Fut,
        Fut: Future<Output = ()> + Send,
    {
        let mut pending = FuturesUnordered::new();

        for observer in self.observers.iter() {
            let observer = Arc::clone(observer);
            let job = ObserverJobLogContext::from(job);
            let event = event.clone();
            pending.push(notify_observer(callback_name, job, notify(observer, event)));
        }

        while pending.next().await.is_some() {}
    }
}

#[derive(Debug)]
struct ObserverJobLogContext {
    job_id: Uuid,
    job_type: String,
    organization_id: Option<Uuid>,
    run_number: i32,
    attempt: i32,
    max_attempts: i32,
    worker_id: String,
}

impl From<&ObservedJob> for ObserverJobLogContext {
    fn from(job: &ObservedJob) -> Self {
        Self {
            job_id: job.job_id,
            job_type: job.job_type.to_string(),
            organization_id: job.organization_id,
            run_number: job.run_number,
            attempt: job.attempt,
            max_attempts: job.max_attempts,
            worker_id: job.worker_id.clone(),
        }
    }
}

async fn notify_observer<F>(callback_name: &'static str, job: ObserverJobLogContext, future: F)
where
    F: Future<Output = ()> + Send,
{
    match tokio::time::timeout(OBSERVER_TIMEOUT, AssertUnwindSafe(future).catch_unwind()).await {
        Ok(Ok(())) => {}
        Ok(Err(panic_payload)) => {
            let panic_message = panic_payload_message(&*panic_payload);
            warn!(
                callback_name,
                job_id = %job.job_id,
                job_type = %job.job_type,
                organization_id = ?job.organization_id,
                run_number = job.run_number,
                attempt = job.attempt,
                max_attempts = job.max_attempts,
                worker_id = %job.worker_id,
                panic = %panic_message,
                "job lifecycle observer panicked"
            );
        }
        Err(_) => {
            warn!(
                callback_name,
                job_id = %job.job_id,
                job_type = %job.job_type,
                organization_id = ?job.organization_id,
                run_number = job.run_number,
                attempt = job.attempt,
                max_attempts = job.max_attempts,
                worker_id = %job.worker_id,
                timeout_ms = OBSERVER_TIMEOUT.as_millis(),
                "job lifecycle observer timed out"
            );
        }
    }
}

fn panic_payload_message(panic_payload: &(dyn Any + Send)) -> String {
    if let Some(message) = panic_payload.downcast_ref::<String>() {
        return message.clone();
    }

    if let Some(message) = panic_payload.downcast_ref::<&'static str>() {
        return (*message).to_string();
    }

    "non-string panic payload".to_string()
}