laratext 0.1.0

Laratext for Laravel Rust: translation keys with their source text, and auto-translation with OpenAI, Claude, Google Translate or Translatorio.
Documentation
//! The translators that ship with the package, and the registry `laratext:scan` picks from.

mod claude;
mod google;
mod openai;
mod translatorio;

use std::sync::Arc;

use indexmap::IndexMap;

pub use claude::ClaudeTranslator;
pub use google::GoogleTranslator;
pub use openai::OpenAiTranslator;
pub use translatorio::TranslatorioTranslator;

use crate::translator::{RealSleeper, Sleeper, Translator};

type Factory = Arc<dyn Fn() -> Arc<dyn Translator> + Send + Sync>;

/// The translators by name, the equivalent of `texts.translators` in the PHP package: a name and
/// what makes it. `openai`, `claude`, `google` and `translatorio` are there from the start.
///
/// Each resolution makes a new translator, as `app($class)` does in PHP, so a scan never shares
/// the state of another one.
#[derive(Clone)]
pub struct Translators {
    factories: IndexMap<String, Factory>,
}

impl Translators {
    /// No translators at all. A scan with none registered copies the source text into every
    /// language, which is what the PHP package does when `texts.translators` is empty.
    pub fn empty() -> Self {
        Self {
            factories: IndexMap::new(),
        }
    }

    /// The four translators that ship with the package.
    pub fn bundled() -> Self {
        let mut translators = Self::empty();

        translators.register("openai", OpenAiTranslator::new);
        translators.register("claude", ClaudeTranslator::new);
        translators.register("google", GoogleTranslator::new);
        translators.register("translatorio", TranslatorioTranslator::new);

        translators
    }

    /// Register a translator under a name, replacing the one with that name.
    pub fn register<T: Translator + 'static>(
        &mut self,
        name: impl Into<String>,
        factory: impl Fn() -> T + Send + Sync + 'static,
    ) {
        self.factories.insert(
            name.into(),
            Arc::new(move || Arc::new(factory()) as Arc<dyn Translator>),
        );
    }

    /// Whether a name is registered.
    pub fn has(&self, name: &str) -> bool {
        self.factories.contains_key(name)
    }

    /// A new translator by name.
    pub fn make(&self, name: &str) -> Option<Arc<dyn Translator>> {
        self.factories.get(name).map(|factory| factory())
    }

    /// The first registered translator, which is the default when the configuration names none.
    pub fn first(&self) -> Option<Arc<dyn Translator>> {
        self.factories.values().next().map(|factory| factory())
    }

    /// The names, in the order they were registered.
    pub fn names(&self) -> Vec<String> {
        self.factories.keys().cloned().collect()
    }
}

impl Default for Translators {
    fn default() -> Self {
        Self::bundled()
    }
}

pub(crate) fn real_sleeper() -> Arc<dyn Sleeper> {
    Arc::new(RealSleeper)
}

/// The body of a response as JSON, or `None` when it is not.
pub(crate) fn json_body(response: &laravel::http::client::Response) -> Option<serde_json::Value> {
    response.json::<serde_json::Value>().ok()
}

/// A string inside the JSON body of a response, by JSON pointer, such as `/error/message`.
pub(crate) fn json_str(response: &laravel::http::client::Response, pointer: &str) -> Option<String> {
    json_body(response)?.pointer(pointer)?.as_str().map(str::to_owned)
}

/// `'⚠️  X answered 429: Slow down'`: what an API said when it refused.
pub(crate) fn refusal(response: &laravel::http::client::Response) -> String {
    json_str(response, "/error/message").unwrap_or_else(|| "no message".to_owned())
}

/// A rate limit or a server error is worth asking again.
pub(crate) fn retryable(response: &laravel::http::client::Response) -> bool {
    response.status() == 429 || response.status().as_u16() >= 500
}

/// PHP's `usleep(min(8, 2 ** $attempt) * 250_000)`, in seconds.
pub(crate) fn backoff_seconds(attempt: u32) -> f64 {
    f64::from(2u32.saturating_pow(attempt).min(8)) * 0.25
}

/// What `json_last_error_msg()` says about a text that did not decode into an array.
pub(crate) fn decode_error(text: &str) -> &'static str {
    if serde_json::from_str::<serde_json::Value>(text).is_err() {
        "Syntax error"
    } else {
        "No error"
    }
}