use std::collections::BTreeMap;
use serde::Serialize;
use sha2::{Digest, Sha256};
use super::store::TextResolver;
use super::tree::{I18nError, LanguageNode, LanguageTree};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScopeDefinition {
pub keys: Vec<String>,
}
impl ScopeDefinition {
pub fn new<I, S>(keys: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
Self {
keys: keys.into_iter().map(Into::into).collect(),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ScopedCatalog {
pub revision: i64,
pub scope: String,
pub messages: BTreeMap<String, LanguageNode>,
}
#[derive(Debug, Clone, Serialize)]
pub struct ScopedClientConfig {
pub locale: String,
#[serde(rename = "fallbackLocale")]
pub fallback_locale: String,
pub scope: String,
pub catalogs: BTreeMap<String, ScopedCatalog>,
#[serde(skip_serializing_if = "Option::is_none")]
pub dictionary: Option<String>,
}
#[derive(Debug, Clone)]
pub struct ClientCatalogs {
resolver: TextResolver,
scopes: BTreeMap<String, ScopeDefinition>,
}
impl ClientCatalogs {
pub fn new(resolver: TextResolver, scopes: BTreeMap<String, ScopeDefinition>) -> Self {
Self { resolver, scopes }
}
pub fn add_scope(&mut self, name: impl Into<String>, definition: ScopeDefinition) -> &mut Self {
self.scopes.insert(name.into(), definition);
self
}
pub fn definition(&self, scope: &str) -> Result<Vec<String>, I18nError> {
let def = self
.scopes
.get(scope)
.ok_or_else(|| I18nError::UnknownScope(scope.to_owned()))?;
for path in &def.keys {
if path.is_empty() || path == "*" || path.starts_with('.') || path.ends_with('.') {
return Err(I18nError::InvalidScopePath(path.clone()));
}
}
let mut paths = def.keys.clone();
paths.sort();
paths.dedup();
Ok(paths)
}
pub fn scope_id(scope: &str, sorted_unique_paths: &[String]) -> String {
let json = serde_json::to_string(sorted_unique_paths).unwrap_or_else(|_| "[]".to_owned());
let hash = hex::encode(Sha256::digest(json.as_bytes()));
format!("{scope}:{}", &hash[..16])
}
pub fn snapshot(&self, scope: &str, locale: &str) -> Result<ScopedCatalog, I18nError> {
let paths = self.definition(scope)?;
let snapshot = self.resolver.snapshot(locale);
let flat = LanguageTree::flatten(&snapshot.messages)?;
let mut visible = BTreeMap::new();
for (key, value) in flat {
if paths.iter().any(|path| {
key == *path
|| (key.starts_with(path.as_str())
&& key.as_bytes().get(path.len()) == Some(&b'.'))
}) {
visible.insert(key, value);
}
}
let messages = LanguageTree::nest(&visible)?;
Ok(ScopedCatalog {
revision: snapshot.revision,
scope: Self::scope_id(scope, &paths),
messages,
})
}
pub fn parse_held_header(held: Option<&str>, expected_scope_id: &str) -> BTreeMap<String, i64> {
let Some(raw) = held else {
return BTreeMap::new();
};
let mut parts = raw.split(';');
if parts.next() != Some(expected_scope_id) {
return BTreeMap::new();
}
let mut have = BTreeMap::new();
for part in parts {
let Some((code, rev_str)) = part.split_once('=') else {
continue;
};
if !code.is_empty()
&& !rev_str.is_empty()
&& rev_str.bytes().all(|b| b.is_ascii_digit())
&& let Ok(rev) = rev_str.parse::<i64>()
{
have.insert(code.to_owned(), rev);
}
}
have
}
pub fn client_config(
&self,
scope: &str,
locale: Option<&str>,
held: Option<&str>,
dictionary_url: Option<String>,
) -> Result<ScopedClientConfig, I18nError> {
let paths = self.definition(scope)?;
let scope_id = Self::scope_id(scope, &paths);
let raw = self.resolver.client_config(locale);
let have = Self::parse_held_header(held, &scope_id);
let mut catalogs = BTreeMap::new();
for (code, cat) in &raw.catalogs {
if have.get(code).copied() != Some(cat.revision) {
catalogs.insert(code.clone(), self.snapshot(scope, code)?);
}
}
Ok(ScopedClientConfig {
locale: raw.locale,
fallback_locale: raw.fallback_locale,
scope: scope_id,
catalogs,
dictionary: dictionary_url,
})
}
pub fn without_held(mut config: ScopedClientConfig, held: Option<&str>) -> ScopedClientConfig {
let have = Self::parse_held_header(held, &config.scope);
config
.catalogs
.retain(|code, cat| have.get(code).copied() != Some(cat.revision));
config
}
pub fn language_revision_header(config: &ScopedClientConfig) -> Option<String> {
if config.catalogs.is_empty() {
return None;
}
let mut parts = Vec::with_capacity(config.catalogs.len() + 1);
parts.push(config.scope.clone());
for (code, catalog) in &config.catalogs {
parts.push(format!("{code}={}", catalog.revision));
}
Some(parts.join(";"))
}
}