Skip to main content

renox_core/db/
mod.rs

1//! Database access (SQLite, or PostgreSQL with the `postgres` feature): the
2//! connection pool, raw SQL, models, queries, pagination, migrations and
3//! factories.
4
5pub(crate) mod auto_migration;
6mod column;
7mod conn;
8pub(crate) mod encrypted;
9mod error;
10mod factory;
11mod from_row;
12mod json;
13mod key;
14mod migrate;
15mod model;
16mod paginate;
17mod query;
18mod query_log;
19pub mod relations;
20pub mod schema;
21#[allow(dead_code)] // used by `db:check` (370.5)
22pub(crate) mod schema_check;
23pub(crate) mod schema_diff;
24pub(crate) mod schema_sql;
25pub mod search;
26mod sequence;
27mod value;
28
29use std::str::FromStr;
30use std::time::Duration;
31
32use anyhow::Context;
33use axum::extract::FromRef;
34use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous};
35
36pub use column::{Col, Comparable, Condition, IntoColumn};
37pub use conn::Conn;
38#[doc(hidden)]
39pub use conn::bounds;
40pub use conn::{Db, Dialect, Executor, FromDb, Row, RowIndex, Sql, Transaction, sql};
41pub(crate) use conn::{RowInner, SchemaEpoch, script};
42pub use encrypted::{Encrypted, Unsealed};
43pub use error::DbError;
44pub use factory::{Factory, FactoryBuilder};
45pub use from_row::FromRow;
46pub use json::{Json, JsonPath, json_index};
47pub use key::{InvalidUlid, ModelKey, Ulid};
48pub use migrate::{Migration, MigrationStatus};
49pub(crate) use migrate::{Migrator, framework_migration};
50pub use model::{Model, ModelHooks};
51pub use paginate::{CursorPage, Page, Paginated, SimplePage};
52pub use query::{Number, Query};
53pub use query_log::capture_queries;
54pub use schema::{ColumnKind, ColumnType, ModelColumn, ModelIndex};
55pub(crate) use sequence::MIGRATION as SEQUENCE_MIGRATION;
56pub use sequence::{NumberFormat, Period, Sequence, SequenceRow};
57/// sqlx, for what Renox's own API doesn't cover: `Db::sqlite()`, `Db::postgres()`,
58/// `Row::sqlite()`, `Row::postgres()` and `DbError::sqlx()` hand out its types.
59/// sqlx may move to a new version in a minor Renox release; see docs/stability.md.
60pub use sqlx;
61pub use value::{DbValue, ToDbValue};
62
63use crate::{AppState, Config};
64
65/// The timestamp type for `created_at`, `updated_at` and `deleted_at`.
66pub type DateTime = chrono::DateTime<chrono::Utc>;
67
68/// Unix seconds (the queue's and webhooks' columns) as a `DateTime`.
69pub(crate) fn from_unix(seconds: i64) -> DateTime {
70    chrono::DateTime::from_timestamp(seconds, 0).unwrap_or_default()
71}
72
73/// The current time, as stored in timestamps: to the microsecond, which is
74/// what PostgreSQL keeps, so a saved model equals the same row read back.
75pub fn now() -> DateTime {
76    use chrono::SubsecRound;
77    chrono::DateTime::<chrono::Utc>::from(crate::clock::system_now()).trunc_subsecs(6)
78}
79
80impl FromRef<AppState> for Db {
81    fn from_ref(state: &AppState) -> Self {
82        state.db.clone()
83    }
84}
85
86/// Opens the pool for `DATABASE_URL`. `postgres://` and `postgresql://` URLs
87/// need the `postgres` feature, `sqlite:` URLs open SQLite, and any other
88/// scheme is refused (so a typo doesn't become a SQLite file).
89///
90/// An in-memory SQLite database (what tests use) is swapped for a fresh
91/// schema in `TEST_DATABASE_URL` when that is set to a PostgreSQL URL (in the
92/// environment or in `.env`), so a test suite can run against PostgreSQL
93/// unchanged.
94pub(crate) async fn connect(config: &Config) -> anyhow::Result<Db> {
95    let url = &config.database_url;
96    if config.database_pool_size == 0 {
97        anyhow::bail!("DATABASE_POOL_SIZE must be at least 1");
98    }
99    if is_postgres(url) {
100        return connect_postgres(url, config, false).await;
101    }
102    if !url.starts_with("sqlite:") {
103        // A typo such as `postgress://` must not become a SQLite file.
104        anyhow::bail!(
105            "DATABASE_URL `{}` must start with sqlite:, postgres:// or postgresql://",
106            redact(url)
107        );
108    }
109    if is_memory(url)
110        && let Some(test_url) = test_database_url().filter(|u| is_postgres(u))
111    {
112        return connect_postgres(&test_url, config, true).await;
113    }
114    let schema = SchemaEpoch::default();
115    let pool = connect_sqlite(config, schema.clone()).await?;
116    Ok(Db::from_sqlite(pool, schema))
117}
118
119/// `TEST_DATABASE_URL` from the environment, else from `.env` in the current
120/// directory (without loading the rest of `.env` into the environment).
121fn test_database_url() -> Option<String> {
122    test_database_url_in(
123        std::env::var("TEST_DATABASE_URL").ok(),
124        std::path::Path::new(".env"),
125    )
126}
127
128/// `env` when set, else `TEST_DATABASE_URL` in the file `dotenv`.
129fn test_database_url_in(env: Option<String>, dotenv: &std::path::Path) -> Option<String> {
130    env.or_else(|| {
131        dotenvy::from_path_iter(dotenv)
132            .ok()?
133            .flatten()
134            .find(|(key, _)| key == "TEST_DATABASE_URL")
135            .map(|(_, url)| url)
136    })
137}
138
139fn is_postgres(url: &str) -> bool {
140    url.starts_with("postgres://") || url.starts_with("postgresql://")
141}
142
143fn is_memory(url: &str) -> bool {
144    url.contains(":memory:") || url.contains("mode=memory")
145}
146
147/// A throwaway database for checks that run migrations: a fresh schema on
148/// PostgreSQL, an in-memory database on SQLite.
149pub(crate) async fn connect_scratch(config: &Config) -> anyhow::Result<Db> {
150    if is_postgres(&config.database_url) {
151        return connect_postgres(&config.database_url, config, true).await;
152    }
153    let mut scratch = config.clone();
154    scratch.database_url = "sqlite::memory:".into();
155    connect(&scratch).await
156}
157
158/// Drops the schema of a database made by [`connect_scratch`] (PostgreSQL only).
159pub(crate) async fn drop_scratch(db: &Db) {
160    if db.dialect() != Dialect::Postgres {
161        return;
162    }
163    let Ok(schema) = sql("SELECT current_schema()").scalar::<String>(db).await else {
164        return;
165    };
166    if schema.starts_with("renox_test_") {
167        let _ = sql(format!("DROP SCHEMA {} CASCADE", quote(&schema)))
168            .execute(db)
169            .await;
170    }
171}
172
173/// Connects to PostgreSQL; with `fresh_schema`, in a new, empty schema of its
174/// own (named `renox_test_…`, left behind for inspection).
175#[cfg(feature = "postgres")]
176async fn connect_postgres(url: &str, config: &Config, fresh_schema: bool) -> anyhow::Result<Db> {
177    use sqlx::postgres::{PgConnectOptions, PgPoolOptions};
178    use sqlx::{ConnectOptions, Connection};
179
180    let failed = || format!("could not connect to the database at `{}`", redact(url));
181    let mut options = PgConnectOptions::from_str(url).with_context(failed)?;
182    if fresh_schema {
183        static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
184        let nanos = std::time::SystemTime::now()
185            .duration_since(std::time::UNIX_EPOCH)
186            .unwrap_or_default()
187            .as_nanos();
188        let schema = format!(
189            "renox_test_{}_{}_{nanos}",
190            std::process::id(),
191            COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
192        );
193        let mut conn = options.connect().await.with_context(failed)?;
194        sqlx::raw_sql(sqlx::AssertSqlSafe(format!(
195            "CREATE SCHEMA {}",
196            quote(&schema)
197        )))
198        .execute(&mut conn)
199        .await
200        .context("could not create a schema for the test")?;
201        conn.close().await.ok();
202        options = options.options([("search_path", schema)]);
203    }
204    if let Some(limit) = config.database_statement_timeout {
205        options = options.options([("statement_timeout", format!("{}ms", limit.as_millis()))]);
206    }
207    let pool_size = config.database_pool_size;
208    // Test suites boot many apps at once; a few connections each keeps them
209    // under the server's limit (100 by default).
210    let pool_size = if fresh_schema {
211        pool_size.min(3)
212    } else {
213        pool_size
214    };
215    let schema = SchemaEpoch::default();
216    let epoch = schema.clone();
217    let pool = PgPoolOptions::new()
218        .max_connections(pool_size)
219        .acquire_timeout(config.database_acquire_timeout)
220        .before_acquire(move |_, meta| {
221            let fresh = !epoch.is_stale(meta.age);
222            Box::pin(async move { Ok(fresh) })
223        })
224        .connect_with(options)
225        .await
226        .with_context(failed)?;
227    Ok(Db::from_postgres(pool, schema))
228}
229
230#[cfg(not(feature = "postgres"))]
231async fn connect_postgres(_url: &str, _config: &Config, _fresh_schema: bool) -> anyhow::Result<Db> {
232    anyhow::bail!(
233        "the database URL points to PostgreSQL, but this build has no PostgreSQL support; \
234         enable the `postgres` feature of `renox`"
235    )
236}
237
238/// The URL with its password hidden, for error messages.
239fn redact(url: &str) -> String {
240    let Some((scheme, rest)) = url.split_once("://") else {
241        return url.to_owned();
242    };
243    match rest.split_once('@') {
244        Some((user, host)) => {
245            let user = user.split_once(':').map_or(user, |(name, _)| name);
246            format!("{scheme}://{user}:***@{host}")
247        }
248        None => url.to_owned(),
249    }
250}
251
252/// How long SQLite waits for a lock before answering "database is locked".
253const BUSY_TIMEOUT: Duration = Duration::from_secs(5);
254
255/// Opens a SQLite pool, creating the file and its directory if needed. File
256/// databases use WAL mode; every connection enforces foreign keys.
257async fn connect_sqlite(config: &Config, schema: SchemaEpoch) -> anyhow::Result<sqlx::SqlitePool> {
258    let url = &config.database_url;
259    let in_memory = is_memory(url);
260
261    let mut options = SqliteConnectOptions::from_str(url)
262        .with_context(|| format!("DATABASE_URL `{url}` is not a valid SQLite URL"))?
263        .create_if_missing(true)
264        .foreign_keys(true)
265        .busy_timeout(BUSY_TIMEOUT);
266    // One busy wait can take the whole `BUSY_TIMEOUT`, so busy errors get that
267    // much on top of the acquire timeout: a long wait still leaves room to
268    // try again (#178).
269    let busy_budget = config.database_acquire_timeout + BUSY_TIMEOUT;
270    if !in_memory {
271        options = options
272            .journal_mode(SqliteJournalMode::Wal)
273            .synchronous(SqliteSynchronous::Normal);
274        if let Some(dir) = options
275            .get_filename()
276            .parent()
277            .filter(|d| !d.as_os_str().is_empty())
278        {
279            std::fs::create_dir_all(dir)
280                .with_context(|| format!("could not create {}", dir.display()))?;
281        }
282        prepare_file(&options, busy_budget).await.with_context(|| {
283            format!("could not open the database at `{url}` (switching it to WAL)")
284        })?;
285    }
286
287    // Each connection to `:memory:` is a separate database, so keep exactly one.
288    let pool = if in_memory {
289        SqlitePoolOptions::new()
290            .max_connections(1)
291            .min_connections(1)
292            .idle_timeout(None)
293            .max_lifetime(None)
294    } else {
295        // Connections opened before a migration would read the old schema.
296        SqlitePoolOptions::new()
297            .max_connections(config.database_pool_size)
298            .before_acquire(move |_, meta| {
299                let fresh = !schema.is_stale(meta.age);
300                Box::pin(async move { Ok(fresh) })
301            })
302    }
303    .acquire_timeout(if in_memory {
304        // The one connection is busy for a moment at most, unless a task
305        // waits for itself (a query through `&db` while its own transaction
306        // is open): fail such a test fast instead of letting it hang.
307        config.database_acquire_timeout.min(Duration::from_secs(2))
308    } else {
309        config.database_acquire_timeout
310    });
311    let pool = if in_memory {
312        // sqlx opens the first connection within `acquire_timeout` too, and on a
313        // busy machine that can take longer than the 2 s above: try again until
314        // the configured timeout has passed.
315        let budget = config.database_acquire_timeout;
316        retry_while(budget, is_pool_timeout, || {
317            pool.clone().connect_with(options.clone())
318        })
319        .await
320    } else {
321        // Another process opening or closing the same file can make SQLite
322        // answer "database is locked" at once (#163), or wait in the busy
323        // handler past the pool's deadline.
324        retry_while(busy_budget, is_busy_or_pool_timeout, || {
325            pool.clone().connect_with(options.clone())
326        })
327        .await
328    };
329    pool.with_context(|| format!("could not open the database at `{url}`"))
330}
331
332/// Opens a file database once before its pool does, so the file exists and is
333/// in WAL mode. Switching to WAL takes an exclusive lock, so processes opening
334/// a brand-new file together (`serve` and `route:list`, say) contend for it:
335/// SQLite answers some of them "database is locked" at once, and a wait in the
336/// busy handler could outlast the pool's acquire timeout (#163). Busy errors
337/// are retried until `budget` has passed; this one connection has no acquire
338/// deadline. Once the file is in WAL mode, the pool's connections don't need
339/// the exclusive lock.
340async fn prepare_file(options: &SqliteConnectOptions, budget: Duration) -> Result<(), sqlx::Error> {
341    use sqlx::{ConnectOptions, Connection};
342
343    // A short busy wait per try: connections switching a new file to WAL
344    // together can each wait for the others' lock, and with the usual five
345    // seconds the first try alone used up the whole budget (#163).
346    let options = options.clone().busy_timeout(Duration::from_millis(100));
347    let conn = retry_while(budget, is_busy, || options.connect()).await?;
348    conn.close().await
349}
350
351/// Whether SQLite answered `SQLITE_BUSY` or `SQLITE_LOCKED` (or one of their
352/// extended codes).
353fn is_busy(error: &sqlx::Error) -> bool {
354    let Some(code) = error
355        .as_database_error()
356        .and_then(|e| e.code())
357        .and_then(|code| code.parse::<i32>().ok())
358    else {
359        return false;
360    };
361    matches!(code & 0xff, 5 | 6)
362}
363
364fn is_busy_or_pool_timeout(error: &sqlx::Error) -> bool {
365    is_busy(error) || is_pool_timeout(error)
366}
367
368fn is_pool_timeout(error: &sqlx::Error) -> bool {
369    matches!(error, sqlx::Error::PoolTimedOut)
370}
371
372/// Runs `open` again, after a short pause, while it fails with an error
373/// `retryable` accepts and `budget` hasn't passed since the first try (but at
374/// least three times); any other result is returned as it is.
375async fn retry_while<T, F>(
376    budget: Duration,
377    retryable: fn(&sqlx::Error) -> bool,
378    mut open: impl FnMut() -> F,
379) -> Result<T, sqlx::Error>
380where
381    F: std::future::Future<Output = Result<T, sqlx::Error>>,
382{
383    let start = tokio::time::Instant::now();
384    let mut tries = 0;
385    loop {
386        tries += 1;
387        match open().await {
388            // At least three tries: one try can wait out a whole busy timeout
389            // (as long as the budget) before it fails (#163).
390            Err(e) if retryable(&e) && (start.elapsed() < budget || tries < 3) => {
391                tracing::debug!("opening the database failed ({e}); trying again");
392                // 25–75 ms, so processes that collided don't collide again.
393                let jitter = u64::from(rand::random::<u8>()) * 50 / 255;
394                tokio::time::sleep(Duration::from_millis(25 + jitter)).await;
395            }
396            result => return result,
397        }
398    }
399}
400
401/// Quotes an identifier (the same on SQLite and PostgreSQL), e.g. `order` -> `"order"`.
402pub(crate) fn quote(ident: &str) -> String {
403    format!("\"{}\"", ident.replace('"', "\"\""))
404}
405
406/// Implements sqlx's traits for a type stored as text through `Display` and
407/// `FromStr` (what `#[derive(DbEnum)]` generates), for every database this
408/// build of Renox supports. Chosen when renox-core is compiled, so apps don't
409/// need to know which features it has.
410#[doc(hidden)]
411#[cfg(not(feature = "postgres"))]
412#[macro_export]
413macro_rules! __db_text_type {
414    ($t:ty) => {
415        $crate::__db_text_type_for!($t, $crate::__sqlx::sqlite::Sqlite);
416    };
417}
418
419#[doc(hidden)]
420#[cfg(feature = "postgres")]
421#[macro_export]
422macro_rules! __db_text_type {
423    ($t:ty) => {
424        $crate::__db_text_type_for!($t, $crate::__sqlx::sqlite::Sqlite);
425        $crate::__db_text_type_for!($t, $crate::__sqlx::postgres::Postgres);
426    };
427}
428
429#[doc(hidden)]
430#[macro_export]
431macro_rules! __db_text_type_for {
432    ($t:ty, $db:ty) => {
433        impl $crate::__sqlx::Type<$db> for $t {
434            fn type_info() -> <$db as $crate::__sqlx::Database>::TypeInfo {
435                <::std::string::String as $crate::__sqlx::Type<$db>>::type_info()
436            }
437
438            fn compatible(ty: &<$db as $crate::__sqlx::Database>::TypeInfo) -> bool {
439                <::std::string::String as $crate::__sqlx::Type<$db>>::compatible(ty)
440            }
441        }
442
443        impl<'r> $crate::__sqlx::Decode<'r, $db> for $t {
444            fn decode(
445                value: <$db as $crate::__sqlx::Database>::ValueRef<'r>,
446            ) -> ::std::result::Result<Self, $crate::__sqlx::error::BoxDynError> {
447                let text = <::std::string::String as $crate::__sqlx::Decode<$db>>::decode(value)?;
448                text.parse::<$t>().map_err(::std::convert::Into::into)
449            }
450        }
451    };
452}
453
454#[cfg(test)]
455mod tests {
456    use std::sync::atomic::{AtomicU32, Ordering};
457    use std::time::Duration;
458
459    use super::{
460        is_busy, is_busy_or_pool_timeout, is_pool_timeout, redact, retry_while,
461        test_database_url_in,
462    };
463    use crate::db::error::fake;
464
465    #[test]
466    fn urls_lose_only_their_password() {
467        assert_eq!(
468            redact("postgres://app:secret@db:5432/app"),
469            "postgres://app:***@db:5432/app"
470        );
471        // A user without a password still gets the mask; no `@` or no
472        // scheme leaves the URL as it is.
473        assert_eq!(redact("postgres://app@db/app"), "postgres://app:***@db/app");
474        assert_eq!(redact("postgres://db/app"), "postgres://db/app");
475        assert_eq!(redact("sqlite:app.db"), "sqlite:app.db");
476    }
477
478    #[test]
479    fn busy_errors_and_pool_timeouts() {
480        for code in ["5", "6", "517", "261"] {
481            assert!(is_busy(&fake::coded(Some(code))), "{code}");
482        }
483        assert!(!is_busy(&fake::coded(Some("19"))));
484        assert!(!is_busy(&fake::coded(Some("40001")))); // not a number
485        assert!(!is_busy(&fake::coded(None)));
486        assert!(!is_busy(&sqlx::Error::PoolTimedOut));
487        assert!(is_busy_or_pool_timeout(&sqlx::Error::PoolTimedOut));
488        assert!(is_busy_or_pool_timeout(&fake::coded(Some("5"))));
489        assert!(!is_busy_or_pool_timeout(&sqlx::Error::PoolClosed));
490    }
491
492    /// The environment wins; else `.env` is read for that one key; a
493    /// missing file or key gives nothing.
494    #[test]
495    fn the_test_database_url_comes_from_the_environment_or_dotenv() {
496        let dir = tempfile::tempdir().unwrap();
497        let dotenv = dir.path().join(".env");
498        assert_eq!(test_database_url_in(None, &dotenv), None);
499        std::fs::write(
500            &dotenv,
501            "APP_NAME=x\nTEST_DATABASE_URL=postgres://t@localhost/t\n",
502        )
503        .unwrap();
504        assert_eq!(
505            test_database_url_in(None, &dotenv).as_deref(),
506            Some("postgres://t@localhost/t")
507        );
508        assert_eq!(
509            test_database_url_in(Some("postgres://env/e".into()), &dotenv).as_deref(),
510            Some("postgres://env/e")
511        );
512        std::fs::write(&dotenv, "APP_NAME=x\n").unwrap();
513        assert_eq!(test_database_url_in(None, &dotenv), None);
514    }
515
516    /// A file database in directories that don't exist yet: they're made.
517    /// An in-memory one waits at most 2 s for its one connection.
518    #[tokio::test]
519    async fn sqlite_makes_directories_and_caps_the_in_memory_wait() {
520        let dir = tempfile::tempdir().unwrap();
521        let config = crate::Config {
522            database_url: format!("sqlite://{}/a/b/app.db", dir.path().display()),
523            ..crate::Config::default()
524        };
525        let pool = super::connect_sqlite(&config, Default::default())
526            .await
527            .unwrap();
528        assert!(dir.path().join("a/b/app.db").exists());
529        pool.close().await;
530
531        let config = crate::Config {
532            database_url: "sqlite::memory:".into(),
533            database_acquire_timeout: Duration::from_secs(30),
534            ..crate::Config::default()
535        };
536        let pool = super::connect_sqlite(&config, Default::default())
537            .await
538            .unwrap();
539        assert_eq!(pool.options().get_acquire_timeout(), Duration::from_secs(2));
540        assert_eq!(pool.options().get_max_connections(), 1);
541    }
542
543    /// Pools opening one brand-new file database at once all open it (#163).
544    #[tokio::test(flavor = "multi_thread", worker_threads = 8)]
545    async fn pools_opening_a_new_file_together_all_open_it() {
546        for _ in 0..10 {
547            let dir = tempfile::tempdir().unwrap();
548            let config = crate::Config {
549                database_url: format!("sqlite://{}/app.db", dir.path().display()),
550                database_acquire_timeout: Duration::from_secs(5),
551                ..crate::Config::default()
552            };
553            let opening: Vec<_> = (0..8)
554                .map(|_| {
555                    let config = config.clone();
556                    tokio::spawn(async move {
557                        super::connect_sqlite(&config, Default::default())
558                            .await
559                            .map(|_| ())
560                    })
561                })
562                .collect();
563            for task in opening {
564                task.await.unwrap().expect("every pool opens the new file");
565            }
566        }
567    }
568
569    /// A slow first connection doesn't fail an in-memory app's boot (#144).
570    #[tokio::test]
571    async fn opening_retries_pool_timeouts_within_the_budget() {
572        let tries = AtomicU32::new(0);
573        let opened = retry_while(Duration::from_secs(30), is_pool_timeout, || async {
574            match tries.fetch_add(1, Ordering::SeqCst) {
575                0 | 1 => Err(sqlx::Error::PoolTimedOut),
576                _ => Ok("pool"),
577            }
578        })
579        .await;
580        assert_eq!(opened.unwrap(), "pool");
581        assert_eq!(tries.load(Ordering::SeqCst), 3);
582    }
583
584    #[tokio::test]
585    async fn opening_gives_up_after_the_budget_and_on_other_errors() {
586        let tries = AtomicU32::new(0);
587        let opened: Result<(), _> = retry_while(Duration::ZERO, is_pool_timeout, || async {
588            tries.fetch_add(1, Ordering::SeqCst);
589            Err(sqlx::Error::PoolTimedOut)
590        })
591        .await;
592        assert!(matches!(opened, Err(sqlx::Error::PoolTimedOut)));
593        // Three tries even with no budget left: one try can take a whole busy
594        // timeout, which used to leave no time to try again (#163).
595        assert_eq!(
596            tries.load(Ordering::SeqCst),
597            3,
598            "three tries, then no retry past the budget"
599        );
600
601        let tries = AtomicU32::new(0);
602        let opened: Result<(), _> =
603            retry_while(Duration::from_secs(30), is_pool_timeout, || async {
604                tries.fetch_add(1, Ordering::SeqCst);
605                Err(sqlx::Error::PoolClosed)
606            })
607            .await;
608        assert!(matches!(opened, Err(sqlx::Error::PoolClosed)));
609        assert_eq!(
610            tries.load(Ordering::SeqCst),
611            1,
612            "other errors aren't retried"
613        );
614    }
615}