-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontracts.rs
More file actions
907 lines (836 loc) · 30.4 KB
/
Copy pathcontracts.rs
File metadata and controls
907 lines (836 loc) · 30.4 KB
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
//! CG-001 provider-independent data and error contracts shared with the WebView.
use std::collections::HashSet;
use serde::{Deserialize, Serialize};
/// BCP-47-style language identifier.
pub type LanguageCode = String;
/// Bounded normalized lexical categories accepted from verified sources.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum PartOfSpeech {
Adjective,
Adverb,
Article,
Conjunction,
Determiner,
Interjection,
Noun,
Number,
Numeral,
Particle,
Phrase,
Postposition,
Prefix,
Preposition,
#[serde(rename = "prepositional phrase")]
PrepositionalPhrase,
Pronoun,
#[serde(rename = "proper noun")]
ProperNoun,
Proverb,
Suffix,
Symbol,
Verb,
}
impl PartOfSpeech {
pub fn as_str(self) -> &'static str {
match self {
Self::Adjective => "adjective",
Self::Adverb => "adverb",
Self::Article => "article",
Self::Conjunction => "conjunction",
Self::Determiner => "determiner",
Self::Interjection => "interjection",
Self::Noun => "noun",
Self::Number => "number",
Self::Numeral => "numeral",
Self::Particle => "particle",
Self::Phrase => "phrase",
Self::Postposition => "postposition",
Self::Prefix => "prefix",
Self::Preposition => "preposition",
Self::PrepositionalPhrase => "prepositional phrase",
Self::Pronoun => "pronoun",
Self::ProperNoun => "proper noun",
Self::Proverb => "proverb",
Self::Suffix => "suffix",
Self::Symbol => "symbol",
Self::Verb => "verb",
}
}
pub fn from_normalized(value: &str) -> Option<Self> {
match value
.trim()
.replace(['_', '-'], " ")
.to_lowercase()
.as_str()
{
"adjective" => Some(Self::Adjective),
"adverb" => Some(Self::Adverb),
"article" => Some(Self::Article),
"conjunction" => Some(Self::Conjunction),
"determiner" => Some(Self::Determiner),
"interjection" => Some(Self::Interjection),
"noun" => Some(Self::Noun),
"number" => Some(Self::Number),
"numeral" => Some(Self::Numeral),
"particle" => Some(Self::Particle),
"phrase" => Some(Self::Phrase),
"postposition" => Some(Self::Postposition),
"prefix" => Some(Self::Prefix),
"preposition" => Some(Self::Preposition),
"prepositional phrase" => Some(Self::PrepositionalPhrase),
"pronoun" => Some(Self::Pronoun),
"proper noun" => Some(Self::ProperNoun),
"proverb" => Some(Self::Proverb),
"suffix" => Some(Self::Suffix),
"symbol" => Some(Self::Symbol),
"verb" => Some(Self::Verb),
_ => None,
}
}
}
/// Rectangle in global physical screen pixels.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PhysicalRect {
pub x: f64,
pub y: f64,
pub width: f64,
pub height: f64,
}
/// Immutable native selection correlated by a monotonic identifier.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SelectionSnapshot {
pub id: u64,
pub text: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub example_sentence: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub source_application_id: Option<String>,
pub bounds_physical_px: Vec<PhysicalRect>,
pub anchor_physical_px: PhysicalRect,
pub captured_at_epoch_ms: u64,
}
/// User-selectable application color theme.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Theme {
System,
Light,
Dark,
}
/// Application chrome language. Lexical content keeps its own language codes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum UiLocale {
#[serde(rename = "en")]
English,
#[serde(rename = "zh-CN")]
SimplifiedChinese,
}
/// Online translation service selected by the user.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum TranslationProviderId {
Google,
Baidu,
Microsoft,
}
/// Microsoft Translator offers separate public and China sovereign clouds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum MicrosoftCloud {
Global,
China,
}
/// Schema-versioned, non-secret application preferences.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UserSettings {
pub schema_version: u8,
pub enabled: bool,
pub source_language: LanguageCode,
pub target_language: LanguageCode,
pub start_at_login: bool,
pub theme: Theme,
pub max_selection_code_points: usize,
pub ui_locale: UiLocale,
pub translation_provider: TranslationProviderId,
pub microsoft_cloud: MicrosoftCloud,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub microsoft_region: Option<String>,
}
impl UserSettings {
/// Selection overlay has no target picker; the saved default is authoritative.
pub fn apply_to_selection_request(&self, request: TranslationRequest) -> TranslationRequest {
TranslationRequest {
target_language: self.target_language.clone(),
..request
}
}
}
/// Validated request passed to a translation provider.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TranslationRequest {
pub selection_id: u64,
pub text: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub example_sentence: Option<String>,
pub source_language: LanguageCode,
pub target_language: LanguageCode,
}
/// Provider-independent translation response.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TranslationSense {
pub text: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub part_of_speech: Option<PartOfSpeech>,
pub rank: u8,
pub is_primary: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub confidence: Option<f64>,
}
/// Provider-independent translation response.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TranslationResult {
pub selection_id: u64,
pub translated_text: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub detected_source_language: Option<LanguageCode>,
pub effective_source_language: LanguageCode,
pub target_language: LanguageCode,
#[serde(skip_serializing_if = "Option::is_none")]
pub part_of_speech: Option<PartOfSpeech>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub senses: Vec<TranslationSense>,
}
/// One locally stored lexical item with independent demand and recall signals.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VocabularySenseSummary {
pub id: i64,
pub text: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub part_of_speech: Option<PartOfSpeech>,
pub rank: u8,
pub is_primary: bool,
}
/// One locally stored lexical item with independent demand and recall signals.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VocabularyEntry {
pub id: i64,
pub source_text: String,
pub translated_text: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub example_sentence: Option<String>,
pub requested_source_language: LanguageCode,
pub effective_source_language: LanguageCode,
pub target_language: LanguageCode,
#[serde(skip_serializing_if = "Option::is_none")]
pub part_of_speech: Option<PartOfSpeech>,
#[serde(default)]
pub senses: Vec<VocabularySenseSummary>,
pub lookup_count: u64,
pub recall_score: f64,
pub effective_recall: f64,
pub familiarity_level: u8,
pub review_count: u64,
pub correct_count: u64,
pub wrong_count: u64,
pub correct_streak: u64,
pub wrong_streak: u64,
pub last_seen_epoch_ms: u64,
#[serde(skip_serializing_if = "Option::is_none")]
pub last_reviewed_epoch_ms: Option<u64>,
}
/// Monotonic invalidation signal emitted after native vocabulary state changes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum VocabularyRevisionKind {
Added,
Updated,
Deleted,
LanguageCorrected,
PracticeReviewed,
Activated,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VocabularyRevision {
pub revision: u64,
pub kind: VocabularyRevisionKind,
#[serde(skip_serializing_if = "Option::is_none")]
pub entry_id: Option<i64>,
}
/// Locally derived relationship between two vocabulary entries.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RelatedVocabulary {
pub entry: VocabularyEntry,
pub reason: String,
}
/// Multiple-choice translation prompt selected entirely from local entries.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PracticeQuestion {
pub entry_id: i64,
pub source_text: String,
pub effective_source_language: LanguageCode,
pub target_language: LanguageCode,
pub choices: Vec<String>,
}
/// Result returned only after a practice answer is submitted.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PracticeOutcome {
pub correct: bool,
pub correct_translation: String,
pub entry: VocabularyEntry,
}
/// One pinned, app-curated textbook artifact offered for native installation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TextbookCatalogItem {
pub id: String,
pub title: String,
pub source_language: LanguageCode,
pub target_language: LanguageCode,
pub version: String,
pub download_url: String,
pub expected_bytes: u64,
pub sha256: String,
pub license: String,
pub attribution: String,
pub source_url: String,
}
/// Installed textbook metadata safe to expose without local file paths.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InstalledTextbook {
pub id: String,
pub title: String,
pub source_language: LanguageCode,
pub target_language: LanguageCode,
pub version: String,
pub license: String,
pub attribution: String,
pub source_url: String,
pub entry_count: u64,
pub installed_at_epoch_ms: u64,
pub active: bool,
/// True when this verified artifact predates the current lexical metadata importer.
pub metadata_refresh_available: bool,
pub lexical_refresh_status: String,
}
/// One normalized dictionary entry imported from a validated textbook.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TextbookEntry {
pub id: i64,
pub textbook_id: String,
pub source_text: String,
pub translated_text: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub phonetic_symbols: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub part_of_speech: Option<PartOfSpeech>,
pub source_language: LanguageCode,
pub target_language: LanguageCode,
}
/// Bounded page used for textbook browsing and search.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TextbookEntryPage {
pub entries: Vec<TextbookEntry>,
pub total: u64,
pub offset: u64,
pub limit: u64,
}
/// Outcome of idempotently adding a textbook entry to the personal wordbook.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TextbookPromotionResult {
pub vocabulary_entry_id: i64,
pub inserted: bool,
}
/// Durable attribution retained by a personal entry after its textbook is removed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VocabularyProvenance {
pub textbook_id: String,
pub textbook_title: String,
pub textbook_version: String,
pub license: String,
pub attribution: String,
pub source_url: String,
pub source_text: String,
pub translated_text: String,
pub promoted_at_epoch_ms: u64,
}
/// A related lexical item with identities that cannot be confused across stores.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RelatedWord {
pub kind: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub vocabulary_entry_id: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub textbook_entry_id: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub textbook_id: Option<String>,
pub source_text: String,
pub translated_text: String,
pub source_language: LanguageCode,
pub target_language: LanguageCode,
#[serde(skip_serializing_if = "Option::is_none")]
pub part_of_speech: Option<PartOfSpeech>,
pub reason: String,
pub promoted: bool,
pub origins: Vec<RelatedOrigin>,
}
/// Display-safe origin metadata retained when identical related pairs are merged.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RelatedOrigin {
pub kind: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub textbook_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub textbook_title: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(
rename_all = "camelCase",
rename_all_fields = "camelCase",
tag = "kind"
)]
pub enum RelatedFilter {
Morpheme { morpheme_id: String },
Translation { vocabulary_sense_id: i64 },
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VocabularySenseDetail {
pub id: i64,
pub text: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub part_of_speech: Option<PartOfSpeech>,
pub rank: u8,
pub is_primary: bool,
pub textbook_word_count: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VocabularyMorpheme {
pub id: String,
pub display: String,
pub kind: String,
pub accessible_label: String,
pub textbook_word_count: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "kebab-case")]
pub enum MeaningRefreshStatus {
Available,
Unsupported,
Offline,
UnavailableLegacy,
FailedRetryable { reason: String },
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VocabularyDetail {
pub entry: VocabularyEntry,
pub senses: Vec<VocabularySenseDetail>,
pub morphemes: Vec<VocabularyMorpheme>,
pub meaning_refresh: MeaningRefreshStatus,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FilteredRelatedWord {
pub key: String,
pub source_text: String,
pub translated_text: String,
pub source_language: LanguageCode,
pub target_language: LanguageCode,
#[serde(skip_serializing_if = "Option::is_none")]
pub part_of_speech: Option<PartOfSpeech>,
#[serde(skip_serializing_if = "Option::is_none")]
pub saved_vocabulary_entry_id: Option<i64>,
pub origins: Vec<RelatedOrigin>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RelatedWordPage {
pub items: Vec<FilteredRelatedWord>,
pub total: u64,
pub offset: u64,
pub limit: u64,
pub relation_label: String,
}
/// User-selectable prompt direction for local practice.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum PracticeDirection {
Random,
SourceToTarget,
TargetToSource,
}
/// Persisted study preferences, deliberately separate from application settings.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PracticePreferences {
pub direction: PracticeDirection,
}
/// Direction-neutral multiple-choice prompt selected from personal vocabulary.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StudyPracticeQuestion {
pub entry_id: i64,
pub direction: PracticeDirection,
pub prompt: String,
pub prompt_language: LanguageCode,
pub answer_language: LanguageCode,
#[serde(skip_serializing_if = "Option::is_none")]
pub prompt_part_of_speech: Option<PartOfSpeech>,
pub choices: Vec<StudyPracticeChoice>,
}
/// One undecorated answer identity plus optional source-backed lexical metadata.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StudyPracticeChoice {
pub value: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub part_of_speech: Option<PartOfSpeech>,
}
/// Direction-aware result returned only after one explicit submission.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StudyPracticeOutcome {
pub correct: bool,
pub correct_answer: String,
pub direction: PracticeDirection,
pub entry: VocabularyEntry,
}
/// Stable error categories safe to expose across IPC.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum AppErrorCode {
PermissionDenied,
UnsupportedControl,
NoSelection,
MissingCredential,
InvalidCredential,
ApiRestricted,
BillingRequired,
QuotaExceeded,
Offline,
Timeout,
ServiceUnavailable,
InvalidLanguagePair,
Internal,
}
/// Stable error envelope without credentials or raw provider bodies.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AppError {
pub code: AppErrorCode,
pub message: String,
pub retryable: bool,
}
impl AppError {
/// Creates a stable application error.
pub fn new(code: AppErrorCode, message: impl Into<String>, retryable: bool) -> Self {
Self {
code,
message: message.into(),
retryable,
}
}
}
/// Semantic validation applied after deserialization at trust boundaries.
pub trait ValidateContract {
/// Rejects values that are structurally valid but semantically unsafe.
fn validate(&self) -> Result<(), AppError>;
}
const JS_SAFE_INTEGER_MAX: u64 = 9_007_199_254_740_991;
fn validation_error(message: impl Into<String>) -> AppError {
AppError::new(AppErrorCode::Internal, message, false)
}
impl ValidateContract for SelectionSnapshot {
fn validate(&self) -> Result<(), AppError> {
if self.id > JS_SAFE_INTEGER_MAX
|| self.captured_at_epoch_ms > JS_SAFE_INTEGER_MAX
|| self.text.trim().is_empty()
|| !valid_example_sentence(self.example_sentence.as_deref())
{
return Err(validation_error("selection violates schema constraints"));
}
if self.bounds_physical_px.is_empty()
|| self
.bounds_physical_px
.iter()
.chain(std::iter::once(&self.anchor_physical_px))
.any(|rect| {
!rect.x.is_finite()
|| !rect.y.is_finite()
|| !rect.width.is_finite()
|| !rect.height.is_finite()
|| rect.width <= 0.0
|| rect.height <= 0.0
})
{
return Err(validation_error(
"selection bounds must be finite and positive",
));
}
Ok(())
}
}
impl ValidateContract for UserSettings {
fn validate(&self) -> Result<(), AppError> {
if self.schema_version != 2
|| self.source_language.trim().is_empty()
|| self.target_language.trim().is_empty()
|| self.max_selection_code_points == 0
|| u64::try_from(self.max_selection_code_points)
.map(|value| value > JS_SAFE_INTEGER_MAX)
.unwrap_or(true)
|| self
.microsoft_region
.as_ref()
.is_some_and(|region| region.trim().is_empty() || region.len() > 64)
{
return Err(validation_error("settings violate schema constraints"));
}
Ok(())
}
}
impl ValidateContract for TranslationRequest {
fn validate(&self) -> Result<(), AppError> {
if self.selection_id > JS_SAFE_INTEGER_MAX
|| self.text.trim().is_empty()
|| self.source_language.trim().is_empty()
|| self.target_language.trim().is_empty()
|| !valid_example_sentence(self.example_sentence.as_deref())
{
return Err(validation_error(
"translation request contains an empty field",
));
}
Ok(())
}
}
fn valid_example_sentence(value: Option<&str>) -> bool {
value.is_none_or(|value| !value.trim().is_empty() && value.chars().count() <= 5_000)
}
impl ValidateContract for TranslationResult {
fn validate(&self) -> Result<(), AppError> {
if self.selection_id > JS_SAFE_INTEGER_MAX
|| self.translated_text.trim().is_empty()
|| self.effective_source_language.trim().is_empty()
|| self.target_language.trim().is_empty()
|| self
.detected_source_language
.as_ref()
.is_some_and(|language| language.trim().is_empty())
{
return Err(validation_error(
"translation result contains an empty field",
));
}
if self.senses.len() > 32 {
return Err(validation_error("translation result has too many senses"));
}
if !self.senses.is_empty() {
let mut primary_count = 0;
let mut keys = HashSet::new();
for (expected_rank, sense) in self.senses.iter().enumerate() {
if sense.text.trim().is_empty()
|| !sense.confidence.is_none_or(f64::is_finite)
|| usize::from(sense.rank) != expected_rank
|| !keys.insert((sense.text.trim().to_lowercase(), sense.part_of_speech))
{
return Err(validation_error("translation senses are invalid"));
}
if sense.is_primary {
primary_count += 1;
if sense.text != self.translated_text || sense.rank != 0 {
return Err(validation_error("translation primary sense does not match"));
}
}
}
if primary_count != 1 {
return Err(validation_error(
"translation result requires one primary sense",
));
}
}
Ok(())
}
}
impl ValidateContract for TextbookCatalogItem {
fn validate(&self) -> Result<(), AppError> {
let required = [
self.id.as_str(),
self.title.as_str(),
self.source_language.as_str(),
self.target_language.as_str(),
self.version.as_str(),
self.license.as_str(),
self.attribution.as_str(),
];
if required.iter().any(|value| value.trim().is_empty())
|| !self.download_url.starts_with("https://")
|| !self.source_url.starts_with("https://")
|| self.expected_bytes == 0
|| self.expected_bytes > JS_SAFE_INTEGER_MAX
|| self.sha256.len() != 64
|| !self
.sha256
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
{
return Err(validation_error("textbook catalog item is unsafe"));
}
Ok(())
}
}
impl ValidateContract for AppError {
fn validate(&self) -> Result<(), AppError> {
if self.message.trim().is_empty() {
return Err(validation_error("error message must not be empty"));
}
Ok(())
}
}
/// Decodes JSON and applies the contract's semantic validation.
pub fn decode_validated<T>(raw: &str) -> Result<T, AppError>
where
T: for<'de> Deserialize<'de> + ValidateContract,
{
let value: T = serde_json::from_str(raw)
.map_err(|_| validation_error("contract JSON could not be decoded"))?;
value.validate()?;
Ok(value)
}
#[cfg(test)]
mod tests {
#[test]
fn related_filters_accept_renderer_payloads_and_round_trip() {
for payload in [
serde_json::json!({ "kind": "translation", "vocabularySenseId": 11 }),
serde_json::json!({ "kind": "morpheme", "morphemeId": "en-root-duce" }),
] {
let filter: super::RelatedFilter =
serde_json::from_value(payload.clone()).expect("renderer filter must deserialize");
assert_eq!(serde_json::to_value(filter).unwrap(), payload);
}
}
use super::{
decode_validated, AppError, SelectionSnapshot, StudyPracticeQuestion, TranslationRequest,
TranslationResult, UserSettings, VocabularyRevision,
};
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct Fixtures {
selection: SelectionSnapshot,
settings: UserSettings,
translation_request: TranslationRequest,
translation_result: TranslationResult,
study_practice_question: StudyPracticeQuestion,
vocabulary_revision: VocabularyRevision,
error: AppError,
errors: Vec<AppError>,
}
#[test]
fn shared_json_fixtures_deserialize_and_round_trip() {
let raw = include_str!("../../src/contracts/fixtures.json");
let fixtures: Fixtures = serde_json::from_str(raw).expect("fixtures must deserialize");
assert_eq!(fixtures.selection.id, 42);
assert_eq!(fixtures.settings.schema_version, 2);
assert_eq!(fixtures.translation_request.selection_id, 42);
assert_eq!(fixtures.translation_result.selection_id, 42);
assert_eq!(fixtures.study_practice_question.choices[0].value, "短暂的");
assert!(fixtures.error.retryable);
assert_eq!(fixtures.vocabulary_revision.revision, 1);
let original: serde_json::Value = serde_json::from_str(raw).expect("valid JSON");
let round_trips = [
serde_json::to_value(&fixtures.selection).expect("selection serializes"),
serde_json::to_value(&fixtures.settings).expect("settings serialize"),
serde_json::to_value(&fixtures.translation_request).expect("request serializes"),
serde_json::to_value(&fixtures.translation_result).expect("result serializes"),
serde_json::to_value(&fixtures.study_practice_question)
.expect("study question serializes"),
serde_json::to_value(&fixtures.vocabulary_revision).expect("revision serializes"),
serde_json::to_value(&fixtures.error).expect("error serializes"),
serde_json::to_value(&fixtures.errors).expect("errors serialize"),
];
assert_eq!(round_trips[0], original["selection"]);
assert_eq!(round_trips[1], original["settings"]);
assert_eq!(round_trips[2], original["translationRequest"]);
assert_eq!(round_trips[3], original["translationResult"]);
assert_eq!(round_trips[4], original["studyPracticeQuestion"]);
assert_eq!(round_trips[5], original["vocabularyRevision"]);
assert_eq!(round_trips[6], original["error"]);
assert_eq!(round_trips[7], original["errors"]);
}
#[test]
fn validated_decode_rejects_semantically_invalid_contracts() {
let invalid = r#"{
"id": 1,
"text": "",
"boundsPhysicalPx": [{"x": 0.0, "y": 0.0, "width": 1.0, "height": 1.0}],
"anchorPhysicalPx": {"x": 0.0, "y": 0.0, "width": 1.0, "height": 1.0},
"capturedAtEpochMs": 1
}"#;
assert!(decode_validated::<SelectionSnapshot>(invalid).is_err());
let invalid_example = r#"{
"id": 1,
"text": "word",
"exampleSentence": " ",
"boundsPhysicalPx": [{"x": 0.0, "y": 0.0, "width": 1.0, "height": 1.0}],
"anchorPhysicalPx": {"x": 0.0, "y": 0.0, "width": 1.0, "height": 1.0},
"capturedAtEpochMs": 1
}"#;
assert!(decode_validated::<SelectionSnapshot>(invalid_example).is_err());
let invalid_result = r#"{
"selectionId": 1,
"translatedText": "hola",
"detectedSourceLanguage": "",
"effectiveSourceLanguage": "en",
"targetLanguage": "es"
}"#;
assert!(decode_validated::<TranslationResult>(invalid_result).is_err());
let unknown_part_of_speech = r#"{
"selectionId": 1,
"translatedText": "hola",
"effectiveSourceLanguage": "en",
"targetLanguage": "es",
"partOfSpeech": "oracle"
}"#;
assert!(serde_json::from_str::<TranslationResult>(unknown_part_of_speech).is_err());
}
#[test]
fn selection_translation_uses_the_saved_target_language() {
let raw = include_str!("../../src/contracts/fixtures.json");
let fixtures: Fixtures = serde_json::from_str(raw).expect("fixtures must deserialize");
let mut settings = fixtures.settings;
settings.target_language = "zh-CN".into();
let request = TranslationRequest {
selection_id: 7,
text: "persistence".into(),
example_sentence: None,
source_language: "auto".into(),
target_language: "en".into(),
};
let applied = settings.apply_to_selection_request(request);
assert_eq!(applied.target_language, "zh-CN");
assert_eq!(applied.source_language, "auto");
assert_eq!(applied.text, "persistence");
}
}