arcature 0.1.2

Arcature: an opinionated full-stack Rust web framework. One package, batteries included.
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
//! Job subsystem error types.
//!
//! Each error is a typed enum (no raw `String` errors). The handler-returned
//! [`JobError`] carries the retry classification the handler decides; the
//! framework never reclassifies.

use std::fmt;

use sqlx::Error as SqlxError;

// ---------------------------------------------------------------------------
// JobError — the error a handler returns.
// ---------------------------------------------------------------------------

/// The error a job handler returns.
///
/// The handler, not the framework, decides whether a failure is retryable.
/// The framework respects that classification: [`Retryable`](Self::Retryable)
/// is retried per backoff (bounded by `max_attempts`); [`Permanent`](Self::Permanent)
/// is marked dead immediately.
#[derive(Debug)]
pub enum JobError {
    /// Transient: retry per backoff, bounded by `max_attempts`; dead when exhausted.
    Retryable(Box<dyn std::error::Error + Send + Sync + 'static>),
    /// Permanent: dead immediately, never retried.
    Permanent(Box<dyn std::error::Error + Send + Sync + 'static>),
}

impl JobError {
    /// Wrap a retryable error.
    pub fn retryable<E>(error: E) -> Self
    where
        E: std::error::Error + Send + Sync + 'static,
    {
        Self::Retryable(Box::new(error))
    }

    /// Wrap a permanent error.
    pub fn permanent<E>(error: E) -> Self
    where
        E: std::error::Error + Send + Sync + 'static,
    {
        Self::Permanent(Box::new(error))
    }

    /// A retryable error from a displayable message.
    pub fn retryable_msg<M>(message: M) -> Self
    where
        M: Into<String>,
    {
        Self::Retryable(Box::new(MessageError(message.into())))
    }

    /// A permanent error from a displayable message.
    pub fn permanent_msg<M>(message: M) -> Self
    where
        M: Into<String>,
    {
        Self::Permanent(Box::new(MessageError(message.into())))
    }

    /// Whether this is a retryable error.
    pub fn is_retryable(&self) -> bool {
        matches!(self, Self::Retryable(_))
    }

    /// Whether this is a permanent error.
    pub fn is_permanent(&self) -> bool {
        matches!(self, Self::Permanent(_))
    }

    /// The message stored in `last_error` (truncated to 4096 bytes on a UTF-8
    /// char boundary). The payload is never part of this message.
    pub(crate) fn stored_message(&self) -> String {
        truncate_for_storage(&self.to_string())
    }
}

impl fmt::Display for JobError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Retryable(inner) => write!(f, "retryable: {inner}"),
            Self::Permanent(inner) => write!(f, "permanent: {inner}"),
        }
    }
}

impl std::error::Error for JobError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Retryable(inner) | Self::Permanent(inner) => Some(inner.as_ref()),
        }
    }
}

/// A simple string-backed error used by [`JobError::retryable_msg`] and
/// [`JobError::permanent_msg`].
#[derive(Debug)]
pub struct MessageError(pub String);

impl fmt::Display for MessageError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for MessageError {}

/// The maximum number of bytes stored in `last_error`.
pub(crate) const LAST_ERROR_MAX_BYTES: usize = 4096;

/// Truncate a string for storage in `last_error`, on a UTF-8 char boundary,
/// with an ellipsis.
pub(crate) fn truncate_for_storage(value: &str) -> String {
    if value.len() <= LAST_ERROR_MAX_BYTES {
        return value.to_string();
    }
    let mut end = LAST_ERROR_MAX_BYTES;
    while end > 0 && !value.is_char_boundary(end) {
        end -= 1;
    }
    let mut truncated = String::from(&value[..end]);
    truncated.push_str("...");
    truncated
}

// ---------------------------------------------------------------------------
// EnqueueError
// ---------------------------------------------------------------------------

/// An error from enqueueing a job.
#[derive(Debug)]
pub enum EnqueueError {
    /// The event payload could not be serialized.
    Serialize { source: serde_json::Error },
    /// The payload exceeded the size limit.
    PayloadTooLarge { size: usize, limit: usize },
    /// The job kind was invalid.
    InvalidKind { reason: String },
    /// A database error during the insert.
    Database { source: SqlxError },
}

impl EnqueueError {
    pub(crate) fn serialize(source: serde_json::Error) -> Self {
        Self::Serialize { source }
    }
    pub(crate) fn payload_too_large(size: usize, limit: usize) -> Self {
        Self::PayloadTooLarge { size, limit }
    }
    pub(crate) fn invalid_kind(reason: impl Into<String>) -> Self {
        Self::InvalidKind {
            reason: reason.into(),
        }
    }
    pub(crate) fn database(source: SqlxError) -> Self {
        Self::Database { source }
    }
}

impl fmt::Display for EnqueueError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Serialize { source } => write!(f, "job payload serialization failed: {source}"),
            Self::PayloadTooLarge { size, limit } => {
                write!(
                    f,
                    "job payload too large: {size} bytes exceeds {limit}-byte limit"
                )
            }
            Self::InvalidKind { reason } => write!(f, "invalid job kind: {reason}"),
            Self::Database { source } => write!(f, "job enqueue database error: {source}"),
        }
    }
}

impl std::error::Error for EnqueueError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Serialize { source } => Some(source),
            Self::Database { source } => Some(source),
            _ => None,
        }
    }
}

impl From<SqlxError> for EnqueueError {
    fn from(source: SqlxError) -> Self {
        Self::database(source)
    }
}

// ---------------------------------------------------------------------------
// RegisterError
// ---------------------------------------------------------------------------

/// An error from registering a job handler.
#[derive(Debug)]
pub enum RegisterError {
    /// A handler is already registered for this kind and version.
    AlreadyRegistered { kind: String, version: i16 },
    /// The job kind was invalid.
    InvalidKind { reason: String },
    /// The payload version was invalid (must be >= 1).
    InvalidVersion { version: i16 },
}

impl RegisterError {
    pub(crate) fn already_registered(kind: impl Into<String>, version: i16) -> Self {
        Self::AlreadyRegistered {
            kind: kind.into(),
            version,
        }
    }
    pub(crate) fn invalid_kind(reason: impl Into<String>) -> Self {
        Self::InvalidKind {
            reason: reason.into(),
        }
    }
    pub(crate) fn invalid_version(version: i16) -> Self {
        Self::InvalidVersion { version }
    }
}

impl fmt::Display for RegisterError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::AlreadyRegistered { kind, version } => {
                write!(
                    f,
                    "handler already registered for kind {kind:?} version {version}"
                )
            }
            Self::InvalidKind { reason } => write!(f, "invalid job kind: {reason}"),
            Self::InvalidVersion { version } => {
                write!(f, "invalid payload version {version}: must be >= 1")
            }
        }
    }
}

impl std::error::Error for RegisterError {}

// ---------------------------------------------------------------------------
// WorkerError
// ---------------------------------------------------------------------------

/// An error from the worker lifecycle (not from individual job execution).
///
/// Per-job failures (panic, malformed, unknown, timeout) are not
/// [`WorkerError`] variants; they become dead or retry rows. `WorkerError`
/// is only lifecycle failure (the worker cannot keep running).
#[derive(Debug)]
pub enum WorkerError {
    /// The worker configuration was invalid.
    InvalidConfig { source: WorkerConfigError },
    /// The retry policy was invalid.
    InvalidRetryPolicy { source: RetryPolicyError },
    /// A database error in the claim/sweep/heartbeat path.
    Database { source: SqlxError },
}

impl WorkerError {
    pub(crate) fn database(source: SqlxError) -> Self {
        Self::Database { source }
    }
}

impl fmt::Display for WorkerError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidConfig { source } => write!(f, "worker config invalid: {source}"),
            Self::InvalidRetryPolicy { source } => {
                write!(f, "worker retry policy invalid: {source}")
            }
            Self::Database { source } => write!(f, "worker database error: {source}"),
        }
    }
}

impl std::error::Error for WorkerError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::InvalidConfig { source } => Some(source),
            Self::InvalidRetryPolicy { source } => Some(source),
            Self::Database { source } => Some(source),
        }
    }
}

impl From<SqlxError> for WorkerError {
    fn from(source: SqlxError) -> Self {
        Self::database(source)
    }
}

impl From<WorkerConfigError> for WorkerError {
    fn from(source: WorkerConfigError) -> Self {
        Self::InvalidConfig { source }
    }
}

impl From<RetryPolicyError> for WorkerError {
    fn from(source: RetryPolicyError) -> Self {
        Self::InvalidRetryPolicy { source }
    }
}

// ---------------------------------------------------------------------------
// MigrateError
// ---------------------------------------------------------------------------

/// An error from applying the jobs schema migrations.
#[derive(Debug)]
pub enum MigrateError {
    /// A database error during migration.
    Database { source: SqlxError },
}

impl MigrateError {
    pub(crate) fn database(source: SqlxError) -> Self {
        Self::Database { source }
    }
}

impl fmt::Display for MigrateError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Database { source } => write!(f, "arcature_jobs migration failed: {source}"),
        }
    }
}

impl std::error::Error for MigrateError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Database { source } => Some(source),
        }
    }
}

impl From<SqlxError> for MigrateError {
    fn from(source: SqlxError) -> Self {
        Self::database(source)
    }
}

// ---------------------------------------------------------------------------
// RetryPolicyError
// ---------------------------------------------------------------------------

/// An error from an invalid retry policy.
#[derive(Debug, Clone, PartialEq)]
pub enum RetryPolicyError {
    /// The multiplier is NaN or infinite.
    MultiplierNotFinite { multiplier: f64 },
    /// The multiplier is negative (would produce a negative delay).
    MultiplierNegative { multiplier: f64 },
}

impl fmt::Display for RetryPolicyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MultiplierNotFinite { multiplier } => {
                write!(
                    f,
                    "retry multiplier ({multiplier}) must be finite; a NaN or infinite multiplier would produce an invalid delay"
                )
            }
            Self::MultiplierNegative { multiplier } => {
                write!(
                    f,
                    "retry multiplier ({multiplier}) must not be negative; a negative multiplier would produce a negative delay"
                )
            }
        }
    }
}

impl std::error::Error for RetryPolicyError {}

// ---------------------------------------------------------------------------
// WorkerConfigError
// ---------------------------------------------------------------------------

/// An error from an invalid worker configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WorkerConfigError {
    /// The job timeout exceeds the lease (would guarantee duplicate delivery).
    JobTimeoutExceedsLease {
        job_timeout: std::time::Duration,
        lease: std::time::Duration,
    },
    /// The heartbeat interval is not below the lease (would be futile).
    HeartbeatIntervalNotBelowLease {
        heartbeat_interval: std::time::Duration,
        lease: std::time::Duration,
    },
}

impl fmt::Display for WorkerConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::JobTimeoutExceedsLease { job_timeout, lease } => {
                write!(
                    f,
                    "job_timeout ({job_timeout:?}) must not exceed lease ({lease:?}); a timeout longer than the lease would guarantee duplicate delivery"
                )
            }
            Self::HeartbeatIntervalNotBelowLease {
                heartbeat_interval,
                lease,
            } => {
                write!(
                    f,
                    "heartbeat_interval ({heartbeat_interval:?}) must be below lease ({lease:?}); a heartbeat at or above the lease would never refresh in time"
                )
            }
        }
    }
}

impl std::error::Error for WorkerConfigError {}

// ---------------------------------------------------------------------------
// SchedulerError
// ---------------------------------------------------------------------------

/// A typed error from the scheduler.
#[derive(Debug)]
pub enum SchedulerError {
    /// A job could not be enqueued.
    Enqueue(EnqueueError),
}

impl fmt::Display for SchedulerError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Enqueue(e) => write!(f, "scheduler enqueue failed: {e}"),
        }
    }
}

impl std::error::Error for SchedulerError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Enqueue(e) => Some(e),
        }
    }
}

impl From<EnqueueError> for SchedulerError {
    fn from(e: EnqueueError) -> Self {
        Self::Enqueue(e)
    }
}