mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! The message set in force for the running invocation.
//!
//! The language is settled once, as early as both deciding layers are in hand,
//! and every place that writes prose for a person reads it from here. Threading
//! the set through every signature instead would put a translation argument on
//! functions that have nothing to do with translation, and a failure raised
//! deep in the call graph would still have no way to reach it.
//!
//! What is shared between threads is the *decision*, not the set. A loaded set
//! carries a memoizer that cannot be shared, so each thread builds its own from
//! the shared decision and keeps it for as long as that decision stands. The
//! reader sees one language either way, which is the only thing that matters.
//!
//! Nothing here can stop the work. A language this build does not carry, or a
//! set that will not load, leaves a working language in force rather than
//! losing the invocation: the reason a message exists is to explain something,
//! and failing to explain it is worse than explaining it in another language.

use super::{negotiate, Messages};
use crate::error::Result;
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::RwLock;
use unic_langid::LanguageIdentifier;

/// The language every human-facing line of this invocation is written in.
///
/// Replaceable rather than write-once because a test harness drives more than
/// one invocation inside a single process, and freezing the first language
/// would make every later invocation lie about which one it chose. The product
/// itself replaces nothing: one process serves one invocation.
static LANGUAGE: RwLock<Option<LanguageIdentifier>> = RwLock::new(None);

thread_local! {
    /// The set this thread built, and the decision it was built from.
    ///
    /// The decision is kept alongside so a thread that outlives a change of
    /// language rebuilds rather than going on answering in the old one.
    static CARRIED: RefCell<Option<(LanguageIdentifier, Rc<Messages>)>> =
        const { RefCell::new(None) };
}

/// Settles the language of this invocation and puts its messages in force.
///
/// `requested` is the mark on the command line and `stored` the value written
/// into the settings file. What neither of them decides is decided by the host,
/// and what the host does not decide is decided by this build.
///
/// A language is put in force even when the answer is a failure, so a caller
/// that mistyped the language still reads the refusal rather than nothing.
///
/// # Errors
///
/// Returns the negotiation failure when a language was asked for and this build
/// does not carry it: a usage failure for the mark on the command line and a
/// configuration failure for the stored value, so the caller learns which of
/// the two is at fault.
pub fn install(requested: Option<&str>, stored: Option<&str>) -> Result<()> {
    match negotiate::negotiate(requested, stored) {
        Ok(language) => {
            choose(language);
            Ok(())
        }
        Err(failure) => {
            // The refusal itself has to be readable, so a working language goes
            // into force before the failure travels back up.
            choose(host_language());
            Err(failure)
        }
    }
}

/// The messages in force, built for this thread.
///
/// A failure can be raised before the language has been settled — while the
/// arguments are still being read, or while the settings file is being opened
/// — and that failure still has to reach the caller. Rather than report such a
/// failure in no language at all, the host's own language serves.
#[must_use]
pub fn active() -> Rc<Messages> {
    let wanted = language();
    CARRIED.with(|cell| {
        let mut slot = cell.borrow_mut();
        if let Some((built_for, carried)) = slot.as_ref() {
            if *built_for == wanted {
                return Rc::clone(carried);
            }
        }
        // A build whose own carried messages will not parse is a defect in the
        // build. The answer to it is a set that carries nothing, so every
        // failure reports in the words its source already wrote, not a lost
        // invocation.
        let carried = Rc::new(
            Messages::load(wanted.clone()).unwrap_or_else(|_| Messages::empty(wanted.clone())),
        );
        *slot = Some((wanted, Rc::clone(&carried)));
        carried
    })
}

/// The language in force, settling on the host's when nothing has been chosen.
fn language() -> LanguageIdentifier {
    if let Some(chosen) = read() {
        return chosen;
    }
    // Recorded rather than recomputed, so asking the host what language it
    // speaks happens once per process however many diagnostics are written.
    let host = host_language();
    choose(host.clone());
    host
}

/// The language the host speaks, or the one built in when it names none.
///
/// Never fails: nothing about a diagnostic is worth losing the invocation over.
fn host_language() -> LanguageIdentifier {
    negotiate::negotiate(None, None)
        .ok()
        .or_else(|| negotiate::parse(negotiate::BUILTIN))
        .unwrap_or_default()
}

/// Reads the decision, treating a poisoned lock as no decision at all.
///
/// A panic while the language was being settled must not turn every later
/// diagnostic into a second panic, so a poisoned lock falls back to the host's
/// language exactly as an unset one does.
fn read() -> Option<LanguageIdentifier> {
    LANGUAGE.read().map_or_else(
        |poisoned| poisoned.into_inner().clone(),
        |guard| guard.clone(),
    )
}

/// Records the decision, treating a poisoned lock as nothing to do.
fn choose(language: LanguageIdentifier) {
    match LANGUAGE.write() {
        Ok(mut guard) => *guard = Some(language),
        Err(poisoned) => *poisoned.into_inner() = Some(language),
    }
}

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

    /// The tests below put a language in force, which is process-wide state, so
    /// they run one at a time and hand the process back as they found it.
    static ORDER: std::sync::Mutex<()> = std::sync::Mutex::new(());

    /// Runs one test with the language to itself, restoring what came before.
    fn alone<T>(body: impl FnOnce() -> T) -> T {
        let guard = ORDER
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let before = read();
        let outcome = body();
        match before {
            Some(language) => choose(language),
            None => clear(),
        }
        drop(guard);
        outcome
    }

    /// Puts nothing in force, so the next reader takes the host's language.
    fn clear() {
        match LANGUAGE.write() {
            Ok(mut guard) => *guard = None,
            Err(poisoned) => *poisoned.into_inner() = None,
        }
    }

    #[test]
    fn the_mark_on_the_command_line_decides_what_is_in_force() {
        alone(|| {
            install(Some("pt-BR"), None).expect("carried by this build");
            assert_eq!(active().language().to_string(), "pt-BR");
        });
    }

    #[test]
    fn the_stored_value_decides_when_no_mark_was_given() {
        alone(|| {
            install(None, Some("pt-BR")).expect("carried by this build");
            assert_eq!(active().language().to_string(), "pt-BR");
        });
    }

    #[test]
    fn the_mark_outranks_the_stored_value() {
        alone(|| {
            install(Some("en"), Some("pt-BR")).expect("carried by this build");
            assert_eq!(active().language().to_string(), "en");
        });
    }

    /// A later invocation inside one process is served its own language, not
    /// the one the first invocation happened to settle on. The set this thread
    /// already built must not outlive the decision it was built from.
    #[test]
    fn a_second_invocation_is_never_served_the_first_ones_language() {
        alone(|| {
            install(Some("en"), None).expect("carried");
            let english = active().format("copy-table", &[("table", "orders")]);
            install(Some("pt-BR"), None).expect("carried");
            let portuguese = active().format("copy-table", &[("table", "orders")]);
            assert_eq!(active().language().to_string(), "pt-BR");
            assert_ne!(english, portuguese, "the set outlived its decision");
        });
    }

    /// A thread that never settled anything still reads the language the
    /// invocation settled on, because the decision is what is shared.
    #[test]
    fn another_thread_reads_the_same_language() {
        alone(|| {
            install(Some("pt-BR"), None).expect("carried");
            let elsewhere = std::thread::spawn(|| active().language().to_string())
                .join()
                .expect("the thread finished");
            assert_eq!(elsewhere, "pt-BR");
        });
    }

    /// A language this build does not carry is refused, and the refusal is
    /// still readable because a working language went into force before it
    /// travelled back up.
    #[test]
    fn a_language_this_build_lacks_is_refused_and_still_leaves_messages_in_force() {
        alone(|| {
            clear();
            let failure = install(Some("klingon"), None).expect_err("must refuse");
            assert_eq!(failure.category(), crate::error::Category::Usage);
            assert!(super::super::SUPPORTED.contains(&active().language().to_string().as_str()));
        });
    }

    /// Nothing in force is not an absence of messages: the host's language
    /// serves, so a failure raised before the language was settled still reads
    /// as prose and not as a bare message name.
    #[test]
    fn a_failure_raised_before_the_language_was_settled_still_reads() {
        alone(|| {
            clear();
            let carried = active();
            assert!(super::super::SUPPORTED.contains(&carried.language().to_string().as_str()));
            assert!(carried.carries("copy-table"));
        });
    }
}