trellis-rs 0.10.17

Curated public Rust facade for Trellis clients and services.
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
use std::collections::hash_map::DefaultHasher;
use std::future::Future;
use std::hash::{Hash, Hasher};
use std::sync::Arc;

use futures_util::future::BoxFuture;
use serde::Serialize;
use serde_json::Value;
use time::format_description::well_known::Rfc3339;
use time::{Duration as TimeDuration, OffsetDateTime};
use ulid::Ulid;

use crate::jobs::active_job::ActiveJob;
use crate::jobs::bindings::{JobsBinding, JobsQueueBinding};
use crate::jobs::events::{
    cancelled_event, completed_event, created_event, failed_event, logged_event, progress_event,
    retry_event, started_event,
};
use crate::jobs::publisher::{JobEventHeaders, JobEventPublisher};
use crate::jobs::runtime_worker::JobCancellationToken;
use crate::jobs::types::{Job, JobContext, JobEventType, JobLogEntry, JobProgress, JobState};

type HeartbeatHook = Arc<dyn Fn() -> BoxFuture<'static, Result<(), String>> + Send + Sync>;

#[derive(Debug, Clone, PartialEq)]
pub enum JobProcessError<E> {
    Retryable(E),
    Failed(E),
}

impl<E> JobProcessError<E> {
    pub fn retryable(error: E) -> Self {
        Self::Retryable(error)
    }

    pub fn failed(error: E) -> Self {
        Self::Failed(error)
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum JobProcessOutcome<TResult> {
    Completed { tries: u64, result: TResult },
    Retry { tries: u64, error: String },
    Failed { tries: u64, error: String },
    Cancelled { tries: u64 },
    Interrupted { tries: u64 },
}

pub trait JobMetaSource {
    fn next_job_id(&self) -> String;
    fn now_iso(&self) -> String;
}

/// Production Trellis metadata source for job ids and timestamps.
#[derive(Debug, Default, Clone, Copy)]
pub struct TrellisJobMetaSource;

impl JobMetaSource for TrellisJobMetaSource {
    fn next_job_id(&self) -> String {
        Ulid::new().to_string()
    }

    fn now_iso(&self) -> String {
        OffsetDateTime::now_utc()
            .format(&Rfc3339)
            .unwrap_or_else(|_| "1970-01-01T00:00:00Z".to_string())
    }
}

#[derive(Debug, thiserror::Error)]
pub enum JobManagerError<E> {
    #[error("missing jobs queue binding for queue type '{queue_type}'")]
    MissingQueueBinding { queue_type: String },
    #[error("failed to serialize job payload: {0}")]
    SerializePayload(serde_json::Error),
    #[error("failed to serialize created event payload: {0}")]
    SerializeEvent(serde_json::Error),
    #[error("failed to serialize job result: {0}")]
    SerializeResult(serde_json::Error),
    #[error("feature '{feature}' is disabled for queue type '{queue_type}'")]
    FeatureDisabled {
        queue_type: String,
        feature: &'static str,
    },
    #[error("invalid transition '{action}' for job '{job_id}' in state '{state:?}'")]
    InvalidTransition {
        job_id: String,
        state: JobState,
        action: &'static str,
    },
    #[error("failed to compute job deadline from timestamp '{timestamp}': {details}")]
    InvalidTimestamp { timestamp: String, details: String },
    #[error("failed to publish job event: {0}")]
    Publish(E),
}

struct JobManagerInner<P, M> {
    publisher: P,
    bindings: JobsBinding,
    meta: M,
}

pub struct JobManager<P, M> {
    inner: Arc<JobManagerInner<P, M>>,
}

impl<P, M> Clone for JobManager<P, M> {
    fn clone(&self) -> Self {
        Self {
            inner: Arc::clone(&self.inner),
        }
    }
}

impl<P, M> JobManager<P, M> {
    pub fn new(publisher: P, bindings: JobsBinding, meta: M) -> Self {
        Self {
            inner: Arc::new(JobManagerInner {
                publisher,
                bindings,
                meta,
            }),
        }
    }

    pub fn publisher(&self) -> &P {
        &self.inner.publisher
    }

    pub fn bindings(&self) -> &JobsBinding {
        &self.inner.bindings
    }
}

impl<P, M> JobManager<P, M>
where
    P: JobEventPublisher,
    M: JobMetaSource,
{
    fn queue_binding(
        &self,
        queue_type: &str,
    ) -> Result<&JobsQueueBinding, JobManagerError<P::Error>> {
        self.inner.bindings.queues.get(queue_type).ok_or_else(|| {
            JobManagerError::MissingQueueBinding {
                queue_type: queue_type.to_string(),
            }
        })
    }

    fn queue_binding_for_job(
        &self,
        job: &Job,
    ) -> Result<&JobsQueueBinding, JobManagerError<P::Error>> {
        self.queue_binding(&job.job_type)
    }

    pub(crate) fn now_iso(&self) -> String {
        self.inner.meta.now_iso()
    }

    pub async fn create<TPayload>(
        &self,
        queue_type: &str,
        payload: TPayload,
    ) -> Result<Job, JobManagerError<P::Error>>
    where
        TPayload: Serialize + Clone,
    {
        let queue = self.queue_binding(queue_type)?;

        let now = self.inner.meta.now_iso();
        let id = self.inner.meta.next_job_id();
        let context = new_job_context(self.inner.meta.next_job_id(), &id, &now);
        let payload_value: Value =
            serde_json::to_value(payload.clone()).map_err(JobManagerError::SerializePayload)?;
        let deadline = compute_deadline(&now, queue.default_deadline_ms).map_err(|details| {
            JobManagerError::InvalidTimestamp {
                timestamp: now.clone(),
                details,
            }
        })?;

        let job = Job {
            id: id.clone(),
            context,
            service: self.inner.bindings.namespace.clone(),
            job_type: queue_type.to_string(),
            state: JobState::Pending,
            payload: payload_value.clone(),
            result: None,
            created_at: now.clone(),
            updated_at: now.clone(),
            started_at: None,
            completed_at: None,
            tries: 0,
            max_tries: queue.max_deliver,
            last_error: None,
            deadline: deadline.clone(),
            progress: None,
            logs: None,
        };

        let created = created_event(
            &job.service,
            &job.job_type,
            &job.id,
            &job.context,
            payload_value,
            queue.max_deliver,
            &now,
            deadline.as_deref(),
        );

        self.publish_queue_event(queue, &id, created.event_type, &created)
            .await?;

        Ok(job)
    }

    pub async fn process<TResult, E, F, Fut>(
        &self,
        job: Job,
        cancellation: JobCancellationToken,
        process: F,
    ) -> Result<JobProcessOutcome<TResult>, JobManagerError<P::Error>>
    where
        TResult: Serialize + Clone,
        E: ToString,
        F: FnOnce(ActiveJob<P, M>) -> Fut,
        Fut: Future<Output = Result<TResult, JobProcessError<E>>>,
    {
        self.process_with_heartbeat(
            job,
            cancellation,
            || async { Err("worker heartbeat unavailable".to_string()) },
            process,
        )
        .await
    }

    pub async fn process_with_heartbeat<TResult, E, HB, HBFut, F, Fut>(
        &self,
        job: Job,
        cancellation: JobCancellationToken,
        heartbeat: HB,
        process: F,
    ) -> Result<JobProcessOutcome<TResult>, JobManagerError<P::Error>>
    where
        TResult: Serialize + Clone,
        E: ToString,
        HB: Fn() -> HBFut + Send + Sync + 'static,
        HBFut: Future<Output = Result<(), String>> + Send + 'static,
        F: FnOnce(ActiveJob<P, M>) -> Fut,
        Fut: Future<Output = Result<TResult, JobProcessError<E>>>,
    {
        let queue = self.queue_binding_for_job(&job)?;

        let tries = job.tries.saturating_add(1);
        let started_at = self.now_iso();
        let started = started_event(
            &job.service,
            &job.job_type,
            &job.id,
            &job.context,
            job.state,
            tries,
            &started_at,
        );
        self.publish_queue_event(queue, &job.id, started.event_type, &started)
            .await?;

        let active_job = self.make_active_job(
            job.clone(),
            tries,
            started_at,
            cancellation.clone(),
            Arc::new(move || Box::pin(heartbeat())),
        );

        match process(active_job).await {
            Ok(result) => {
                if cancellation.is_host_shutdown() {
                    return Ok(JobProcessOutcome::Interrupted { tries });
                }
                if cancellation.is_cancelled() {
                    return Ok(JobProcessOutcome::Cancelled { tries });
                }
                let result_value = serde_json::to_value(result.clone())
                    .map_err(JobManagerError::SerializeResult)?;
                let completed = completed_event(
                    &job.service,
                    &job.job_type,
                    &job.id,
                    &job.context,
                    tries,
                    &self.now_iso(),
                    result_value,
                );
                self.publish_queue_event(queue, &job.id, completed.event_type, &completed)
                    .await?;
                Ok(JobProcessOutcome::Completed { tries, result })
            }
            Err(JobProcessError::Retryable(error)) => {
                if cancellation.is_host_shutdown() {
                    return Ok(JobProcessOutcome::Interrupted { tries });
                }
                if cancellation.is_cancelled() {
                    return Ok(JobProcessOutcome::Cancelled { tries });
                }
                let error = error.to_string();
                let retry = retry_event(
                    &job.service,
                    &job.job_type,
                    &job.id,
                    &job.context,
                    JobState::Active,
                    tries,
                    &self.now_iso(),
                    Some(&error),
                );
                self.publish_queue_event(queue, &job.id, retry.event_type, &retry)
                    .await?;
                Ok(JobProcessOutcome::Retry { tries, error })
            }
            Err(JobProcessError::Failed(error)) => {
                if cancellation.is_host_shutdown() {
                    return Ok(JobProcessOutcome::Interrupted { tries });
                }
                if cancellation.is_cancelled() {
                    return Ok(JobProcessOutcome::Cancelled { tries });
                }
                let error = error.to_string();
                let failed = failed_event(
                    &job.service,
                    &job.job_type,
                    &job.id,
                    &job.context,
                    JobState::Active,
                    tries,
                    &self.now_iso(),
                    &error,
                );
                self.publish_queue_event(queue, &job.id, failed.event_type, &failed)
                    .await?;
                Ok(JobProcessOutcome::Failed { tries, error })
            }
        }
    }

    pub async fn emit_progress(
        &self,
        job: &Job,
        progress: JobProgress,
    ) -> Result<(), JobManagerError<P::Error>> {
        let queue = self.queue_binding_for_job(job)?;
        if !queue.progress {
            return Err(JobManagerError::FeatureDisabled {
                queue_type: queue.queue_type.clone(),
                feature: "progress",
            });
        }
        if job.state != JobState::Active {
            return Err(JobManagerError::InvalidTransition {
                job_id: job.id.clone(),
                state: job.state,
                action: "emit_progress",
            });
        }

        let event = progress_event(
            &job.service,
            &job.job_type,
            &job.id,
            &job.context,
            job.tries,
            &self.now_iso(),
            progress,
        );
        self.publish_queue_event(queue, &job.id, event.event_type, &event)
            .await
    }

    pub async fn emit_log(
        &self,
        job: &Job,
        log: JobLogEntry,
    ) -> Result<(), JobManagerError<P::Error>> {
        let queue = self.queue_binding_for_job(job)?;
        if !queue.logs {
            return Err(JobManagerError::FeatureDisabled {
                queue_type: queue.queue_type.clone(),
                feature: "logs",
            });
        }
        if job.state != JobState::Active {
            return Err(JobManagerError::InvalidTransition {
                job_id: job.id.clone(),
                state: job.state,
                action: "emit_log",
            });
        }

        let event = logged_event(
            &job.service,
            &job.job_type,
            &job.id,
            &job.context,
            job.tries,
            &self.now_iso(),
            vec![log],
        );
        self.publish_queue_event(queue, &job.id, event.event_type, &event)
            .await
    }

    pub async fn cancel(&self, job: &Job) -> Result<(), JobManagerError<P::Error>> {
        let queue = self.queue_binding_for_job(job)?;
        if !matches!(
            job.state,
            JobState::Pending | JobState::Retry | JobState::Active
        ) {
            return Err(JobManagerError::InvalidTransition {
                job_id: job.id.clone(),
                state: job.state,
                action: "cancel",
            });
        }

        let event = cancelled_event(
            &job.service,
            &job.job_type,
            &job.id,
            &job.context,
            job.state,
            job.tries,
            &self.now_iso(),
        );
        self.publish_queue_event(queue, &job.id, event.event_type, &event)
            .await
    }

    pub async fn with_active_job<T, F, Fut>(
        &self,
        job: Job,
        cancellation: JobCancellationToken,
        f: F,
    ) -> Result<T, JobManagerError<P::Error>>
    where
        F: FnOnce(ActiveJob<P, M>) -> Fut,
        Fut: Future<Output = Result<T, JobManagerError<P::Error>>>,
    {
        self.with_active_job_and_heartbeat(
            job,
            cancellation,
            || async { Err("worker heartbeat unavailable".to_string()) },
            f,
        )
        .await
    }

    pub async fn with_active_job_and_heartbeat<T, HB, HBFut, F, Fut>(
        &self,
        job: Job,
        cancellation: JobCancellationToken,
        heartbeat: HB,
        f: F,
    ) -> Result<T, JobManagerError<P::Error>>
    where
        HB: Fn() -> HBFut + Send + Sync + 'static,
        HBFut: Future<Output = Result<(), String>> + Send + 'static,
        F: FnOnce(ActiveJob<P, M>) -> Fut,
        Fut: Future<Output = Result<T, JobManagerError<P::Error>>>,
    {
        let heartbeat: HeartbeatHook = Arc::new(move || Box::pin(heartbeat()));
        f(ActiveJob::new(
            (*self).clone(),
            job,
            cancellation,
            heartbeat,
        ))
        .await
    }

    fn make_active_job(
        &self,
        job: Job,
        tries: u64,
        started_at: String,
        cancellation: JobCancellationToken,
        heartbeat: HeartbeatHook,
    ) -> ActiveJob<P, M> {
        ActiveJob::new(
            (*self).clone(),
            Job {
                state: JobState::Active,
                tries,
                started_at: Some(started_at.clone()),
                updated_at: started_at,
                ..job
            },
            cancellation,
            heartbeat,
        )
    }

    async fn publish_queue_event(
        &self,
        queue: &JobsQueueBinding,
        job_id: &str,
        event_type: JobEventType,
        event: &crate::jobs::types::JobEvent,
    ) -> Result<(), JobManagerError<P::Error>> {
        let payload = serde_json::to_vec(event).map_err(JobManagerError::SerializeEvent)?;
        let subject = format!(
            "{}.{}.{}",
            queue.publish_prefix,
            job_id,
            event_type.as_token()
        );
        self.publisher()
            .publish(subject, JobEventHeaders::from(&event.context), payload)
            .await
            .map_err(JobManagerError::Publish)
    }
}

fn new_job_context(request_id: String, job_id: &str, timestamp: &str) -> JobContext {
    let trace_id = synthesize_trace_id(&request_id, job_id, timestamp);
    let span_id = synthesize_span_id(&trace_id, &request_id);
    let traceparent = format!("00-{trace_id}-{span_id}-01");
    let trace_id = trace_id_from_traceparent(&traceparent)
        .expect("synthesized traceparent should be valid")
        .to_string();
    JobContext {
        request_id,
        trace_id,
        traceparent,
        tracestate: None,
    }
}

fn synthesize_trace_id(request_id: &str, job_id: &str, timestamp: &str) -> String {
    let left = stable_hash64(&(request_id, job_id, timestamp, "trace-left"));
    let right = stable_hash64(&(timestamp, job_id, request_id, "trace-right"));
    let trace_id = format!("{left:016x}{right:016x}");
    if trace_id == "00000000000000000000000000000000" {
        "00000000000000000000000000000001".to_string()
    } else {
        trace_id
    }
}

fn synthesize_span_id(trace_id: &str, request_id: &str) -> String {
    let value = stable_hash64(&(trace_id, request_id, "span"));
    if value == 0 {
        "0000000000000001".to_string()
    } else {
        format!("{value:016x}")
    }
}

fn stable_hash64(value: &impl Hash) -> u64 {
    let mut hasher = DefaultHasher::new();
    value.hash(&mut hasher);
    hasher.finish()
}

pub(crate) fn trace_id_from_traceparent(traceparent: &str) -> Option<&str> {
    let mut parts = traceparent.split('-');
    let version = parts.next()?;
    let trace_id = parts.next()?;
    let span_id = parts.next()?;
    let flags = parts.next()?;
    if parts.next().is_some()
        || version.len() != 2
        || trace_id.len() != 32
        || span_id.len() != 16
        || flags.len() != 2
        || trace_id == "00000000000000000000000000000000"
        || span_id == "0000000000000000"
        || !trace_id.chars().all(|value| value.is_ascii_hexdigit())
        || !span_id.chars().all(|value| value.is_ascii_hexdigit())
    {
        return None;
    }
    Some(trace_id)
}

fn compute_deadline(now: &str, default_deadline_ms: Option<u64>) -> Result<Option<String>, String> {
    let Some(default_deadline_ms) = default_deadline_ms else {
        return Ok(None);
    };
    let parsed = OffsetDateTime::parse(now, &Rfc3339).map_err(|error| error.to_string())?;
    let deadline =
        parsed + TimeDuration::milliseconds(i64::try_from(default_deadline_ms).unwrap_or(i64::MAX));
    deadline
        .format(&Rfc3339)
        .map(Some)
        .map_err(|error| error.to_string())
}