runledger-postgres 0.2.1

PostgreSQL persistence layer for the Runledger durable job and workflow 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
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
use std::{fmt, sync::Arc};

use sqlx::error::ErrorKind;

mod classify;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QueryErrorCategory {
    Conflict,
    Validation,
    Forbidden,
    Internal,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FrameworkConstraintSpec {
    category: QueryErrorCategory,
    code: &'static str,
    client_message: &'static str,
}

impl FrameworkConstraintSpec {
    #[must_use]
    pub const fn new(
        category: QueryErrorCategory,
        code: &'static str,
        client_message: &'static str,
    ) -> Self {
        Self {
            category,
            code,
            client_message,
        }
    }

    #[must_use]
    pub const fn category(&self) -> QueryErrorCategory {
        self.category
    }

    #[must_use]
    pub const fn code(&self) -> &'static str {
        self.code
    }

    #[must_use]
    pub const fn client_message(&self) -> &'static str {
        self.client_message
    }
}

#[derive(Clone)]
pub struct QueryError {
    category: QueryErrorCategory,
    code: &'static str,
    client_message: &'static str,
    sqlstate: Option<String>,
    constraint: Option<String>,
    message: String,
    source: Option<Arc<sqlx::Error>>,
}

impl QueryError {
    #[must_use]
    pub fn from_classified(
        category: QueryErrorCategory,
        code: &'static str,
        client_message: &'static str,
        internal_message: impl Into<String>,
    ) -> Self {
        Self {
            category,
            code,
            client_message,
            sqlstate: None,
            constraint: None,
            message: internal_message.into(),
            source: None,
        }
    }

    #[must_use]
    pub(crate) fn from_classified_sqlx(
        category: QueryErrorCategory,
        code: &'static str,
        client_message: &'static str,
        internal_message: impl Into<String>,
        source: sqlx::Error,
    ) -> Self {
        let (sqlstate, constraint) = source
            .as_database_error()
            .map(|database_error| {
                (
                    database_error.code().map(|code| code.into_owned()),
                    database_error.constraint().map(ToOwned::to_owned),
                )
            })
            .unwrap_or((None, None));

        Self {
            category,
            code,
            client_message,
            sqlstate,
            constraint,
            message: internal_message.into(),
            source: Some(Arc::new(source)),
        }
    }

    #[must_use]
    pub fn from_sqlx_with_constraint_classifier<F>(
        error: sqlx::Error,
        context: Option<&str>,
        classify_constraint: F,
    ) -> Self
    where
        F: Fn(&str) -> Option<FrameworkConstraintSpec>,
    {
        let (sqlstate, constraint, spec, raw_message) = if let Some(db) = error.as_database_error()
        {
            let sqlstate = db.code().map(|code| code.into_owned());
            let constraint = db.constraint().map(ToOwned::to_owned);
            let spec = classify_query_error_with_constraint_classifier(
                &db.kind(),
                sqlstate.as_deref(),
                constraint.as_deref(),
                classify_constraint,
            );
            (sqlstate, constraint, spec, db.message().to_owned())
        } else {
            (
                None,
                None,
                QueryErrorSpec::internal().into(),
                error.to_string(),
            )
        };

        let message = match context {
            Some(ctx) => format!("{ctx}: {raw_message}"),
            None => raw_message,
        };

        Self {
            category: spec.category(),
            code: spec.code(),
            client_message: spec.client_message(),
            sqlstate,
            constraint,
            message,
            source: Some(Arc::new(error)),
        }
    }

    pub(crate) fn from_sqlx(error: sqlx::Error, context: Option<&str>) -> Self {
        Self::from_sqlx_with_constraint_classifier(error, context, |_| None)
    }

    #[must_use]
    pub const fn category(&self) -> QueryErrorCategory {
        self.category
    }

    #[must_use]
    pub const fn code(&self) -> &'static str {
        self.code
    }

    #[must_use]
    pub const fn client_message(&self) -> &'static str {
        self.client_message
    }

    #[must_use]
    pub fn sqlstate(&self) -> Option<&str> {
        self.sqlstate.as_deref()
    }

    #[must_use]
    pub fn constraint(&self) -> Option<&str> {
        self.constraint.as_deref()
    }

    #[must_use]
    pub fn internal_message(&self) -> &str {
        &self.message
    }

    /// Returns the underlying SQLx error for trusted diagnostics.
    ///
    /// Public [`Display`](fmt::Display) and [`Debug`](fmt::Debug) output for
    /// [`QueryError`] is sanitized, but the returned source may contain raw
    /// database details. Do not log or expose it on untrusted boundaries without
    /// redaction.
    #[must_use]
    pub fn source_arc(&self) -> Option<Arc<sqlx::Error>> {
        self.source.clone()
    }

    #[must_use]
    pub fn reclassified_with_constraint_classifier<F>(mut self, classify_constraint: F) -> Self
    where
        F: Fn(&str) -> Option<FrameworkConstraintSpec>,
    {
        let Some(spec) = self.constraint.as_deref().and_then(classify_constraint) else {
            return self;
        };

        self.category = spec.category();
        self.code = spec.code();
        self.client_message = spec.client_message();
        self
    }
}

impl fmt::Debug for QueryError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("QueryError")
            .field("category", &self.category)
            .field("code", &self.code)
            .field("client_message", &self.client_message)
            .field("sqlstate", &self.sqlstate)
            .field("constraint", &self.constraint)
            .field("has_source", &self.source.is_some())
            .finish()
    }
}

impl fmt::Display for QueryError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.client_message)
    }
}

impl std::error::Error for QueryError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.source
            .as_deref()
            .map(|source| source as &(dyn std::error::Error + 'static))
    }
}

#[derive(Debug, Clone, Copy)]
struct QueryErrorSpec {
    category: QueryErrorCategory,
    code: &'static str,
    client_message: &'static str,
}

impl QueryErrorSpec {
    const fn conflict(code: &'static str, client_message: &'static str) -> Self {
        Self {
            category: QueryErrorCategory::Conflict,
            code,
            client_message,
        }
    }

    const fn validation(code: &'static str, client_message: &'static str) -> Self {
        Self {
            category: QueryErrorCategory::Validation,
            code,
            client_message,
        }
    }

    const fn forbidden(code: &'static str, client_message: &'static str) -> Self {
        Self {
            category: QueryErrorCategory::Forbidden,
            code,
            client_message,
        }
    }

    const fn internal() -> Self {
        Self {
            category: QueryErrorCategory::Internal,
            code: "db.query_failed",
            client_message: "Database operation failed.",
        }
    }
}

impl From<QueryErrorSpec> for FrameworkConstraintSpec {
    fn from(spec: QueryErrorSpec) -> Self {
        Self::new(spec.category, spec.code, spec.client_message)
    }
}

#[must_use]
pub fn classify_query_error(
    kind: &ErrorKind,
    sqlstate: Option<&str>,
    constraint: Option<&str>,
) -> FrameworkConstraintSpec {
    classify_query_error_with_constraint_classifier(kind, sqlstate, constraint, |_| None)
}

#[must_use]
pub fn classify_query_error_with_constraint_classifier<F>(
    kind: &ErrorKind,
    sqlstate: Option<&str>,
    constraint: Option<&str>,
    classify_constraint: F,
) -> FrameworkConstraintSpec
where
    F: Fn(&str) -> Option<FrameworkConstraintSpec>,
{
    if let Some(spec) = constraint.and_then(classify_constraint) {
        return spec;
    }

    classify_database_error(kind, sqlstate, constraint).into()
}

fn classify_database_error(
    kind: &ErrorKind,
    sqlstate: Option<&str>,
    constraint: Option<&str>,
) -> QueryErrorSpec {
    if let Some(spec) = constraint.and_then(classify_constraint) {
        return spec;
    }

    match (kind, sqlstate) {
        (ErrorKind::UniqueViolation, _) | (_, Some("23505")) => {
            QueryErrorSpec::conflict("db.unique_violation", "Resource already exists.")
        }
        (ErrorKind::ForeignKeyViolation, _) | (_, Some("23503")) => QueryErrorSpec::validation(
            "db.related_resource_missing",
            "Related resource does not exist.",
        ),
        (_, Some("23001")) => QueryErrorSpec::validation(
            "db.related_resource_still_referenced",
            "Related resource is still referenced and cannot be deleted.",
        ),
        (ErrorKind::CheckViolation, _) | (_, Some("23514")) => QueryErrorSpec::validation(
            "db.business_rule_violation",
            "Request violates a business rule.",
        ),
        (ErrorKind::NotNullViolation, _) | (_, Some("23502")) => {
            QueryErrorSpec::validation("db.required_field_missing", "Required data is missing.")
        }
        (_, Some("42501")) => {
            QueryErrorSpec::forbidden("db.permission_denied", "Operation is not allowed.")
        }
        _ => QueryErrorSpec::internal(),
    }
}

fn classify_constraint(constraint: &str) -> Option<QueryErrorSpec> {
    classify::classify_constraint(constraint)
}

#[must_use]
pub fn classify_framework_constraint(constraint: &str) -> Option<FrameworkConstraintSpec> {
    classify_constraint(constraint).map(FrameworkConstraintSpec::from)
}

#[must_use]
pub fn has_framework_constraint_classifier(constraint: &str) -> bool {
    classify_framework_constraint(constraint).is_some()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn classifies_job_idempotency_constraint() {
        let spec = classify_database_error(
            &ErrorKind::UniqueViolation,
            Some("23505"),
            Some("uq_job_queue_type_idempotency_org"),
        );
        assert_eq!(spec.category, QueryErrorCategory::Conflict);
        assert_eq!(spec.code, "job.already_enqueued");
    }

    #[test]
    fn classifies_global_job_idempotency_constraint() {
        let spec = classify_database_error(
            &ErrorKind::UniqueViolation,
            Some("23505"),
            Some("uq_job_queue_type_idempotency_global"),
        );
        assert_eq!(spec.category, QueryErrorCategory::Conflict);
        assert_eq!(spec.code, "job.already_enqueued");
    }

    #[test]
    fn classifies_workflow_idempotency_constraint() {
        let spec = classify_database_error(
            &ErrorKind::UniqueViolation,
            Some("23505"),
            Some("uq_workflow_runs_type_idempotency_org"),
        );
        assert_eq!(spec.category, QueryErrorCategory::Conflict);
        assert_eq!(spec.code, "workflow.already_enqueued");
    }

    #[test]
    fn classifies_global_workflow_idempotency_constraint() {
        let spec = classify_database_error(
            &ErrorKind::UniqueViolation,
            Some("23505"),
            Some("uq_workflow_runs_type_idempotency_global"),
        );
        assert_eq!(spec.category, QueryErrorCategory::Conflict);
        assert_eq!(spec.code, "workflow.already_enqueued");
    }

    #[test]
    fn classifies_job_definition_fk_constraint() {
        let spec = classify_database_error(
            &ErrorKind::ForeignKeyViolation,
            Some("23503"),
            Some("fk_job_queue_job_type"),
        );
        assert_eq!(spec.category, QueryErrorCategory::Validation);
        assert_eq!(spec.code, "job.definition_not_found");
    }

    #[test]
    fn classifies_job_runtime_config_definition_fk_constraint() {
        let spec = classify_database_error(
            &ErrorKind::ForeignKeyViolation,
            Some("23503"),
            Some("fk_job_runtime_configs_job_type"),
        );
        assert_eq!(spec.category, QueryErrorCategory::Validation);
        assert_eq!(spec.code, "job.definition_not_found");
    }

    #[test]
    fn classifies_job_organization_fk_constraint() {
        let spec = classify_database_error(
            &ErrorKind::ForeignKeyViolation,
            Some("23503"),
            Some("fk_job_queue_organization"),
        );
        assert_eq!(spec.category, QueryErrorCategory::Validation);
        assert_eq!(spec.code, "job.organization_not_found");
    }

    #[test]
    fn classifies_workflow_linkage_symmetry_constraint() {
        let spec = classify_database_error(
            &ErrorKind::CheckViolation,
            Some("23514"),
            Some("os_workflow_job_linkage_symmetry"),
        );
        assert_eq!(spec.category, QueryErrorCategory::Validation);
        assert_eq!(spec.code, "workflow.linkage_symmetry_violation");
    }

    #[test]
    fn classifies_workflow_linkage_symmetry_trigger_table_constraint() {
        let spec = classify_database_error(
            &ErrorKind::CheckViolation,
            Some("23514"),
            Some("os_workflow_job_linkage_symmetry_trigger_table"),
        );
        assert_eq!(spec.category, QueryErrorCategory::Validation);
        assert_eq!(spec.code, "workflow.linkage_symmetry_trigger_table_invalid");
    }

    #[test]
    fn classifies_external_gate_downgrade_blocked_constraint() {
        let spec = classify_database_error(
            &ErrorKind::CheckViolation,
            Some("23514"),
            Some("os_workflow_external_gate_downgrade_waiting_runs_exist"),
        );
        assert_eq!(spec.category, QueryErrorCategory::Validation);
        assert_eq!(spec.code, "workflow.external_gate_downgrade_blocked");
    }

    #[test]
    fn custom_constraint_classifier_takes_precedence() {
        let spec = classify_query_error_with_constraint_classifier(
            &ErrorKind::UniqueViolation,
            Some("23505"),
            Some("os_custom_override"),
            |constraint| {
                (constraint == "os_custom_override").then_some(FrameworkConstraintSpec::new(
                    QueryErrorCategory::Forbidden,
                    "custom.override",
                    "Custom override wins.",
                ))
            },
        );
        assert_eq!(spec.category(), QueryErrorCategory::Forbidden);
        assert_eq!(spec.code(), "custom.override");
        assert_eq!(spec.client_message(), "Custom override wins.");
    }

    #[test]
    fn query_error_debug_omits_internal_message() {
        let error = QueryError::from_classified(
            QueryErrorCategory::Conflict,
            "job.idempotency_conflict",
            "Job enqueue retry conflicts with the existing idempotency key.",
            "internal context includes secret-idempotency-key",
        );

        let debug = format!("{error:?}");
        assert!(debug.contains("job.idempotency_conflict"));
        assert!(!debug.contains("secret-idempotency-key"));

        let display = error.to_string();
        assert_eq!(
            display,
            "Job enqueue retry conflicts with the existing idempotency key."
        );
        assert!(!display.contains("secret-idempotency-key"));
    }

    #[test]
    fn query_error_from_sqlx_uses_sanitized_display_and_debug() {
        let error = QueryError::from_sqlx(
            sqlx::Error::Protocol("internal secret-idempotency-key detail".into()),
            Some("sensitive context"),
        );

        let display = error.to_string();
        assert_eq!(display, "Database operation failed.");
        assert!(!display.contains("secret-idempotency-key"));

        let debug = format!("{error:?}");
        assert!(debug.contains("db.query_failed"));
        assert!(!debug.contains("secret-idempotency-key"));
        assert!(error.internal_message().contains("secret-idempotency-key"));
        assert!(std::error::Error::source(&error).is_some());
        assert!(error.source_arc().is_some());
    }

    #[test]
    fn query_error_from_classified_sqlx_preserves_source_without_leaking_display() {
        let error = QueryError::from_classified_sqlx(
            QueryErrorCategory::Conflict,
            "workflow.release_conflict",
            "Workflow step release conflicted with another workflow mutation.",
            "internal context includes secret-lock-key",
            sqlx::Error::Protocol("database detail includes secret-lock-key".into()),
        );

        assert_eq!(error.category(), QueryErrorCategory::Conflict);
        assert_eq!(error.code(), "workflow.release_conflict");
        assert_eq!(
            error.client_message(),
            "Workflow step release conflicted with another workflow mutation."
        );
        assert!(error.internal_message().contains("secret-lock-key"));
        assert!(error.source_arc().is_some());
        assert!(std::error::Error::source(&error).is_some());

        let display = error.to_string();
        assert_eq!(
            display,
            "Workflow step release conflicted with another workflow mutation."
        );
        assert!(!display.contains("secret-lock-key"));

        let debug = format!("{error:?}");
        assert!(debug.contains("workflow.release_conflict"));
        assert!(debug.contains("has_source: true"));
        assert!(!debug.contains("secret-lock-key"));
    }

    #[test]
    fn classifies_permission_denied() {
        let spec = classify_database_error(&ErrorKind::Other, Some("42501"), None);
        assert_eq!(spec.category, QueryErrorCategory::Forbidden);
        assert_eq!(spec.code, "db.permission_denied");
    }

    #[test]
    fn falls_back_to_internal_for_unmapped_errors() {
        let spec = classify_database_error(&ErrorKind::Other, Some("99999"), Some("not_mapped"));
        assert_eq!(spec.category, QueryErrorCategory::Internal);
        assert_eq!(spec.code, "db.query_failed");
    }
}