cntp_i18n_parlance_source 0.3.0

Support library for integrating cntp-i18n with the Parlance TMS
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
mod parse_raw_string;

use crate::parse_raw_string::parse_raw_string;
use cntp_i18n::{
    I18N_MANAGER, I18nEntry, I18nPluralStringEntry, I18nSource, I18nString, I18nStringPart, Locale,
};
use serde::Deserialize;
use signalr_client::{ArgumentConfiguration, InvocationContext, SignalRClient};
use std::collections::HashMap;
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::sync::{Arc, RwLock};
use tracing::{error, info, warn};
use url::ParseError;
use zed_reqwest::{Client, Url};

pub struct CntpI18nParlanceSource {
    base_url: Url,
    project: String,
    subproject: String,

    crate_name: String,

    entries: Arc<RwLock<HashMap<String, HashMap<String, &'static I18nEntry<'static>>>>>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct ParlanceEntry {
    key: String,
    context: String,
    source: String,
    translation: Vec<ParlanceEntryTranslation>,
    requires_pluralisation: bool,
    comment: Option<String>,
    old_source_string: Option<String>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct ParlanceEntryTranslation {
    plural_type: String,
    translation_content: String,
}

#[derive(Debug)]
pub enum ParlanceSourceError {
    RequestError(zed_reqwest::Error),
    UrlParseError,
}

impl Display for ParlanceSourceError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::RequestError(e) => write!(f, "Request error: {}", e),
            Self::UrlParseError => write!(f, "URL parse error"),
        }
    }
}

impl Error for ParlanceSourceError {}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct SubprojectResponse {
    available_languages: Vec<SubprojectAvailableLanguage>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct SubprojectAvailableLanguage {
    language: String,
}

impl From<ParseError> for ParlanceSourceError {
    fn from(_: ParseError) -> Self {
        ParlanceSourceError::UrlParseError
    }
}

impl From<zed_reqwest::Error> for ParlanceSourceError {
    fn from(value: zed_reqwest::Error) -> Self {
        ParlanceSourceError::RequestError(value)
    }
}

enum SignalRMessage {
    Subscribe {
        project: String,
        subproject: String,
        language: String,
    },
}

enum SignalRHubMessage {
    TranslationUpdated {
        project: String,
        subproject: String,
        language: String,
        data: HashMap<String, Vec<ParlanceEntryTranslation>>,
    },
}

impl CntpI18nParlanceSource {
    pub async fn new(
        base_url: Url,
        project: String,
        subproject: String,
        crate_name: String,
    ) -> Result<Self, ParlanceSourceError> {
        warn!(
            "The Parlance translation source leaks memory! Turn off the Parlance source if you are not using it to translate this application."
        );

        let client = Client::builder().build()?;
        let mut entries = HashMap::new();

        // Find all languages supported by the project
        let response = client
            .get(base_url.join(&format!("api/projects/{}/{}", project, subproject))?)
            .send()
            .await?;

        let response = response.json::<SubprojectResponse>().await?;
        for language in &response.available_languages {
            // Find entries for this language
            let response = client
                .get(base_url.join(&format!(
                    "api/projects/{}/{}/{}/entries",
                    project, subproject, language.language
                ))?)
                .send()
                .await?;

            response.error_for_status_ref()?;

            let parlance_entries = response.json::<Vec<ParlanceEntry>>().await?;

            let mut i18n_entries = HashMap::new();
            for entry in parlance_entries {
                if let Some(i18n_entry) = entry.to_i18n_entry(language.language.clone().into()) {
                    let boxed = Box::new(i18n_entry);
                    i18n_entries.insert(entry.key.clone(), Box::leak(boxed) as &'static I18nEntry);
                }
            }
            entries.insert(language.language.clone(), i18n_entries);
        }

        // let entries = Arc::new(RwLock::new(entries));
        let (tx_signalr, mut rx_signalr) = tokio::sync::mpsc::channel(16);
        let (tx_signalr_ret, mut rx_signalr_ret) = tokio::sync::mpsc::channel(16);

        tokio::spawn({
            let base_url = base_url.clone();
            async move {
                let mut signalr_client = match SignalRClient::connect_with(
                    &format!(
                        "{}:{}",
                        base_url.host_str().unwrap(),
                        base_url.port_or_known_default().unwrap()
                    ),
                    "api/signalr/translator",
                    |c| {
                        if base_url.scheme() == "http" {
                            c.unsecure();
                        }
                    },
                )
                .await
                {
                    Ok(signalr_client) => signalr_client,
                    Err(e) => {
                        error!("Unable to connect to SignalR endpoint: {:?}", e);
                        return;
                    }
                };

                signalr_client.register("TranslationUpdated".into(), {
                    let tx_signalr_ret = tx_signalr_ret.clone();
                    move |cx: InvocationContext| {
                        tokio::spawn({
                            let tx_signalr_ret = tx_signalr_ret.clone();
                            async move {
                                let project = match cx.argument::<String>(0) {
                                    Ok(project) => project,
                                    Err(e) => {
                                        error!("Unable to parse SignalR message: {:?}", e);
                                        return;
                                    }
                                };
                                let subproject = match cx.argument::<String>(1) {
                                    Ok(subproject) => subproject,
                                    Err(e) => {
                                        error!("Unable to parse SignalR message: {:?}", e);
                                        return;
                                    }
                                };
                                let language = match cx.argument::<String>(2) {
                                    Ok(language) => language,
                                    Err(e) => {
                                        error!("Unable to parse SignalR message: {:?}", e);
                                        return;
                                    }
                                };
                                let data = match cx
                                    .argument::<HashMap<String, Vec<ParlanceEntryTranslation>>>(4)
                                {
                                    Ok(data) => data,
                                    Err(e) => {
                                        error!("Unable to parse SignalR message: {:?}", e);
                                        return;
                                    }
                                };

                                let _ = tx_signalr_ret
                                    .send(SignalRHubMessage::TranslationUpdated {
                                        project,
                                        subproject,
                                        language,
                                        data,
                                    })
                                    .await;
                            }
                        });
                    }
                });

                while let Some(message) = rx_signalr.recv().await {
                    match message {
                        SignalRMessage::Subscribe {
                            project,
                            subproject,
                            language,
                        } => {
                            if let Err(e) = signalr_client
                                .invoke_with_args::<String, _>(
                                    "Subscribe".into(),
                                    |c: &mut ArgumentConfiguration| {
                                        c.argument(project.clone())
                                            .argument(subproject.clone())
                                            .argument(language.clone());
                                    },
                                )
                                .await
                            {
                                error!("Unable to subscribe to the project on SignalR: {:?}", e);
                            }
                        }
                    }
                }
            }
        });

        for language in response.available_languages {
            // Subscribe to the SignalR endpoint
            if let Err(e) = tx_signalr
                .send(SignalRMessage::Subscribe {
                    project: project.clone(),
                    subproject: subproject.clone(),
                    language: language.language.clone(),
                })
                .await
            {
                error!("Unable to subscribe to the project on SignalR: {:?}", e);
            }
        }

        let entries = Arc::new(RwLock::new(entries));
        tokio::spawn({
            let project = project.clone();
            let subproject = subproject.clone();
            let weak_entries = Arc::downgrade(&entries);
            async move {
                while let Some(message) = rx_signalr_ret.recv().await {
                    match message {
                        SignalRHubMessage::TranslationUpdated {
                            project: signalr_project,
                            subproject: signalr_subproject,
                            language,
                            data,
                        } => {
                            if signalr_project != project || signalr_subproject != subproject {
                                // This message is not for us
                                return;
                            }

                            let Some(entries) = weak_entries.upgrade() else {
                                return;
                            };

                            let mut entries = entries.write().unwrap();
                            let language_entries = entries.entry(language.clone()).or_default();
                            for (key, translation) in data {
                                let Some(existing_entry) = language_entries.get(&key) else {
                                    // Can't update a key that doesn't already exist
                                    continue;
                                };

                                let Some(new_entry) = entry_translations_to_i18n_entry(
                                    &key,
                                    existing_entry.is_plural(),
                                    language.clone().into(),
                                    &translation,
                                ) else {
                                    continue;
                                };

                                let boxed = Box::new(new_entry);
                                language_entries
                                    .insert(key.clone(), Box::leak(boxed) as &'static I18nEntry);

                                I18N_MANAGER.evict_key(&key);

                                info!("Translation updated: {} {}", language, key);
                            }
                        }
                    }
                }
            }
        });

        Ok(Self {
            base_url,
            project,
            subproject,
            crate_name,
            entries,
        })
    }
}

impl<'a> ParlanceEntry {
    pub fn to_i18n_entry(&self, locale: I18nString) -> Option<I18nEntry<'a>> {
        entry_translations_to_i18n_entry(
            self.key.as_str(),
            self.requires_pluralisation,
            locale,
            &self.translation,
        )
    }
}

fn entry_translations_to_i18n_entry<'a>(
    key: &str,
    requires_pluralisation: bool,
    locale: I18nString,
    translations: &Vec<ParlanceEntryTranslation>,
) -> Option<I18nEntry<'a>> {
    // TODO: Don't leak memory
    if requires_pluralisation {
        let parts_for_plural = |plural_type: &str| -> Option<&'a [I18nStringPart]> {
            let p = parse_raw_string(
                &translations
                    .iter()
                    .find(|t| t.plural_type == plural_type)?
                    .translation_content,
            )
            .iter()
            .map(|part| part.calculate_string_part(key))
            .collect::<Vec<_>>();

            Some(p.leak())
        };

        let zero = parts_for_plural("zero");
        let one = parts_for_plural("one");
        let two = parts_for_plural("two");
        let few = parts_for_plural("few");
        let many = parts_for_plural("many");
        let other = parts_for_plural("other")?;

        let plural_entry = I18nPluralStringEntry {
            locale,
            zero,
            one,
            two,
            few,
            many,
            other,
        };

        Some(I18nEntry::PluralEntry(plural_entry))
    } else {
        let parts = parse_raw_string(&translations.first()?.translation_content)
            .iter()
            .map(|part| part.calculate_string_part(key))
            .collect::<Vec<_>>();
        Some(I18nEntry::Entry(parts.leak()))
    }
}

impl I18nSource for CntpI18nParlanceSource {
    fn lookup(
        &'_ self,
        locale: &Locale,
        id: &str,
        lookup_crate: &str,
    ) -> Option<&'_ I18nEntry<'_>> {
        if self.crate_name != lookup_crate {
            return None;
        }

        let entries = self.entries.read().unwrap();
        for locale in &locale.messages {
            let Some(entries) = entries.get(locale) else {
                continue;
            };

            for (key, entry) in entries {
                if key == id {
                    return Some(entry);
                }
            }
        }
        None
    }
}

pub async fn install_cntp_i18n_parlance_source(
    base_url: Url,
    project: impl Into<String>,
    subproject: impl Into<String>,
    crate_name: impl Into<String>,
) -> Result<(), ParlanceSourceError> {
    let source = CntpI18nParlanceSource::new(
        base_url,
        project.into(),
        subproject.into(),
        crate_name.into(),
    )
    .await?;
    I18N_MANAGER.load_source(source);
    Ok(())
}