-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmsgcat.go
More file actions
1060 lines (959 loc) · 28.2 KB
/
msgcat.go
File metadata and controls
1060 lines (959 loc) · 28.2 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
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package msgcat
import (
"context"
"fmt"
"os"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/loopcontext/msgcat/internal/plural"
"gopkg.in/yaml.v2"
)
//go:generate mockgen -source=$GOFILE -package mock_msgcat -destination=test/mock/$GOFILE
const MessageCatalogNotFound = "Unexpected error in message catalog, language [%s] not found. %s"
const (
// RuntimeKeyPrefix is required for message keys loaded via LoadMessages (e.g. "sys.").
RuntimeKeyPrefix = "sys."
CodeMissingMessage = "msgcat.missing_message"
CodeMissingLanguage = "msgcat.missing_language"
overflowStatKey = "__overflow__"
)
// messageKeyRegex validates message keys: [a-zA-Z0-9_.-]+
var messageKeyRegex = regexp.MustCompile(`^[a-zA-Z0-9_.-]+$`)
var (
simplePlaceholderRegex = regexp.MustCompile(`\{\{([a-zA-Z_][a-zA-Z0-9_.]*)\}\}`)
pluralPlaceholderRegex = regexp.MustCompile(`\{\{plural:([a-zA-Z_][a-zA-Z0-9_.]*)\|((?:[^{}]|\{\{.*?\}\})*)\}\}`)
numberPlaceholderRegex = regexp.MustCompile(`\{\{num:([a-zA-Z_][a-zA-Z0-9_.]*)\}\}`)
datePlaceholderRegex = regexp.MustCompile(`\{\{date:([a-zA-Z_][a-zA-Z0-9_.]*)\}\}`)
)
type MessageCatalog interface {
// LoadMessages adds or replaces messages for a language. Keys must have prefix RuntimeKeyPrefix (e.g. "sys.").
LoadMessages(lang string, messages []RawMessage) error
GetMessageWithCtx(ctx context.Context, msgKey string, params Params) *Message
WrapErrorWithCtx(ctx context.Context, err error, msgKey string, params Params) error
GetErrorWithCtx(ctx context.Context, msgKey string, params Params) error
}
type observerEventType int
const (
observerEventLanguageFallback observerEventType = iota
observerEventLanguageMissing
observerEventMessageMissing
observerEventTemplateIssue
)
type observerEvent struct {
kind observerEventType
requested string
resolved string
lang string
msgKey string
templateIssue string
}
type catalogStats struct {
mu sync.Mutex
languageFallbacks map[string]int
missingLanguages map[string]int
missingMessages map[string]int
templateIssues map[string]int
droppedEvents map[string]int
maxKeys int
lastReloadAt time.Time
}
func sanitizeStatKey(key string) string {
key = strings.TrimSpace(key)
if key == "" {
return "unknown"
}
if len(key) > 120 {
return key[:120]
}
return key
}
func (s *catalogStats) increment(target map[string]int, key string) {
s.mu.Lock()
defer s.mu.Unlock()
if target == nil {
return
}
key = sanitizeStatKey(key)
if s.maxKeys > 0 {
if _, exists := target[key]; !exists {
if _, hasOverflow := target[overflowStatKey]; hasOverflow {
if len(target) >= s.maxKeys {
key = overflowStatKey
}
} else if len(target) >= s.maxKeys-1 {
key = overflowStatKey
}
}
}
target[key]++
}
func (s *catalogStats) incrementLanguageFallback(requestedLang string, resolvedLang string) {
s.increment(s.languageFallbacks, fmt.Sprintf("%s->%s", requestedLang, resolvedLang))
}
func (s *catalogStats) incrementMissingLanguage(lang string) {
s.increment(s.missingLanguages, normalizeLangTag(lang))
}
func (s *catalogStats) incrementMissingMessage(lang string, msgKey string) {
s.increment(s.missingMessages, fmt.Sprintf("%s:%s", lang, msgKey))
}
func (s *catalogStats) incrementTemplateIssue(lang string, msgKey string, issue string) {
s.increment(s.templateIssues, fmt.Sprintf("%s:%s:%s", lang, msgKey, issue))
}
func (s *catalogStats) incrementDroppedEvent(reason string) {
s.increment(s.droppedEvents, reason)
}
func (s *catalogStats) setLastReloadAt(t time.Time) {
s.mu.Lock()
defer s.mu.Unlock()
s.lastReloadAt = t
}
func (s *catalogStats) reset() {
s.mu.Lock()
defer s.mu.Unlock()
s.languageFallbacks = map[string]int{}
s.missingLanguages = map[string]int{}
s.missingMessages = map[string]int{}
s.templateIssues = map[string]int{}
s.droppedEvents = map[string]int{}
s.lastReloadAt = time.Time{}
}
func (s *catalogStats) snapshot() MessageCatalogStats {
s.mu.Lock()
defer s.mu.Unlock()
copyMap := func(input map[string]int) map[string]int {
output := make(map[string]int, len(input))
for k, v := range input {
output[k] = v
}
return output
}
return MessageCatalogStats{
LanguageFallbacks: copyMap(s.languageFallbacks),
MissingLanguages: copyMap(s.missingLanguages),
MissingMessages: copyMap(s.missingMessages),
TemplateIssues: copyMap(s.templateIssues),
DroppedEvents: copyMap(s.droppedEvents),
LastReloadAt: s.lastReloadAt,
}
}
type DefaultMessageCatalog struct {
mu sync.RWMutex
messages map[string]Messages // language -> messages (Set keyed by message key)
runtimeMessages map[string]map[string]RawMessage
cfg Config
stats catalogStats
observerCh chan observerEvent
observerDone chan struct{}
}
func (dmc *DefaultMessageCatalog) readMessagesFromYaml() (map[string]Messages, error) {
resourcePath := dmc.cfg.ResourcePath
if resourcePath == "" {
resourcePath = "./resources/messages"
}
messageFiles, err := os.ReadDir(resourcePath)
if err != nil {
return nil, fmt.Errorf("failed to find messages %v", err)
}
messageByLang := map[string]Messages{}
for _, messageFile := range messageFiles {
fileName := messageFile.Name()
if !strings.HasSuffix(fileName, ".yaml") {
continue
}
var messages Messages
lang := normalizeLangTag(strings.TrimSuffix(fileName, ".yaml"))
yamlFile, err := os.ReadFile(fmt.Sprintf("%s/%s", resourcePath, fileName))
if err != nil {
return nil, fmt.Errorf("failed to read message file: %v", err)
}
err = yaml.Unmarshal(yamlFile, &messages)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal messages: %v", err)
}
if err := normalizeAndValidateMessages(lang, &messages); err != nil {
return nil, err
}
messageByLang[lang] = messages
}
return messageByLang, nil
}
func (dmc *DefaultMessageCatalog) readMessagesFromYamlWithRetry() (map[string]Messages, error) {
retries := dmc.cfg.ReloadRetries
if retries < 0 {
retries = 0
}
delay := dmc.cfg.ReloadRetryDelay
if delay <= 0 {
delay = 50 * time.Millisecond
}
var lastErr error
for attempt := 0; attempt <= retries; attempt++ {
messageByLang, err := dmc.readMessagesFromYaml()
if err == nil {
return messageByLang, nil
}
lastErr = err
if attempt < retries {
time.Sleep(delay)
}
}
return nil, lastErr
}
func (dmc *DefaultMessageCatalog) loadFromYaml() error {
messageByLang, err := dmc.readMessagesFromYamlWithRetry()
if err != nil {
return err
}
dmc.mu.Lock()
defer dmc.mu.Unlock()
if dmc.runtimeMessages != nil {
for lang, runtimeSet := range dmc.runtimeMessages {
msgSet, found := messageByLang[lang]
if !found {
msgSet = Messages{Set: map[string]RawMessage{}}
}
if msgSet.Set == nil {
msgSet.Set = map[string]RawMessage{}
}
for key, msg := range runtimeSet {
msgSet.Set[key] = msg
}
messageByLang[lang] = msgSet
}
}
dmc.messages = messageByLang
dmc.stats.setLastReloadAt(dmc.cfg.NowFn())
return nil
}
func normalizeAndValidateMessages(lang string, messages *Messages) error {
if messages.Default.ShortTpl == "" && messages.Default.LongTpl == "" {
return fmt.Errorf("invalid default message for language %s: at least short or long text is required", lang)
}
if messages.Set == nil {
messages.Set = map[string]RawMessage{}
}
for key, raw := range messages.Set {
if key == "" {
return fmt.Errorf("invalid message key for language %s: key must be non-empty", lang)
}
if !messageKeyRegex.MatchString(key) {
return fmt.Errorf("invalid message key %q for language %s: must match [a-zA-Z0-9_.-]+", key, lang)
}
// Code is optional; leave as-is from YAML
messages.Set[key] = raw
}
return nil
}
func normalizeLangTag(lang string) string {
lang = strings.TrimSpace(strings.ToLower(lang))
lang = strings.ReplaceAll(lang, "_", "-")
return lang
}
func baseLangTag(lang string) string {
if idx := strings.Index(lang, "-"); idx > 0 {
return lang[:idx]
}
return lang
}
func appendLangIfMissing(target *[]string, seen map[string]struct{}, lang string) {
if lang == "" {
return
}
if _, exists := seen[lang]; exists {
return
}
seen[lang] = struct{}{}
*target = append(*target, lang)
}
func isPluralOne(value interface{}) (bool, bool) {
switch typed := value.(type) {
case int:
return typed == 1, true
case int8:
return typed == 1, true
case int16:
return typed == 1, true
case int32:
return typed == 1, true
case int64:
return typed == 1, true
case uint:
return typed == 1, true
case uint8:
return typed == 1, true
case uint16:
return typed == 1, true
case uint32:
return typed == 1, true
case uint64:
return typed == 1, true
case float32:
return typed == 1, true
case float64:
return typed == 1, true
default:
return false, false
}
}
// pluralCountFromParam converts a param value to int for CLDR plural form selection.
func pluralCountFromParam(value interface{}) (int, bool) {
switch typed := value.(type) {
case int:
return typed, true
case int8:
return int(typed), true
case int16:
return int(typed), true
case int32:
return int(typed), true
case int64:
return int(typed), true
case uint:
return int(typed), true
case uint8:
return int(typed), true
case uint16:
return int(typed), true
case uint32:
return int(typed), true
case uint64:
return int(typed), true
case float32:
return int(typed), true
case float64:
return int(typed), true
default:
return 0, false
}
}
// selectCLDRForm returns the template string from forms for the given lang and count, with fallback to other then defaultTpl.
func selectCLDRForm(forms map[string]string, lang string, count int, defaultTpl string) string {
if len(forms) == 0 {
return defaultTpl
}
form := plural.Form(lang, count)
if tpl, ok := forms[form]; ok && tpl != "" {
return tpl
}
if tpl, ok := forms["other"]; ok && tpl != "" {
return tpl
}
return defaultTpl
}
// parsePluralToken extracts param name and content from {{plural:name|content}}.
func parsePluralToken(token string) (paramName string, content string, ok bool) {
matches := pluralPlaceholderRegex.FindStringSubmatch(token)
if len(matches) != 3 {
return "", "", false
}
return matches[1], matches[2], true
}
func toString(value interface{}) string {
switch typed := value.(type) {
case string:
return typed
case int:
return strconv.Itoa(typed)
case int8:
return strconv.FormatInt(int64(typed), 10)
case int16:
return strconv.FormatInt(int64(typed), 10)
case int32:
return strconv.FormatInt(int64(typed), 10)
case int64:
return strconv.FormatInt(typed, 10)
case uint:
return strconv.FormatUint(uint64(typed), 10)
case uint8:
return strconv.FormatUint(uint64(typed), 10)
case uint16:
return strconv.FormatUint(uint64(typed), 10)
case uint32:
return strconv.FormatUint(uint64(typed), 10)
case uint64:
return strconv.FormatUint(typed, 10)
case float32:
return strconv.FormatFloat(float64(typed), 'f', -1, 32)
case float64:
return strconv.FormatFloat(typed, 'f', -1, 64)
case bool:
return strconv.FormatBool(typed)
case time.Time:
return typed.Format(time.RFC3339)
case *time.Time:
if typed == nil {
return "<nil>"
}
return typed.Format(time.RFC3339)
default:
return fmt.Sprintf("%v", value)
}
}
func groupDigits(input string, separator string) string {
if len(input) <= 3 {
return input
}
start := len(input) % 3
if start == 0 {
start = 3
}
var b strings.Builder
b.WriteString(input[:start])
for i := start; i < len(input); i += 3 {
b.WriteString(separator)
b.WriteString(input[i : i+3])
}
return b.String()
}
func formatNumberByLang(lang string, value interface{}) (string, bool) {
decimalSeparator := "."
groupSeparator := ","
switch baseLangTag(lang) {
case "es", "pt", "fr", "de", "it":
decimalSeparator = ","
groupSeparator = "."
}
formatFloat := func(number float64) string {
s := strconv.FormatFloat(number, 'f', -1, 64)
parts := strings.SplitN(s, ".", 2)
intPart := parts[0]
sign := ""
if strings.HasPrefix(intPart, "-") {
sign = "-"
intPart = strings.TrimPrefix(intPart, "-")
}
intPart = sign + groupDigits(intPart, groupSeparator)
if len(parts) == 1 {
return intPart
}
return intPart + decimalSeparator + parts[1]
}
switch typed := value.(type) {
case int:
value := strconv.Itoa(typed)
if strings.HasPrefix(value, "-") {
return "-" + groupDigits(strings.TrimPrefix(value, "-"), groupSeparator), true
}
return groupDigits(value, groupSeparator), true
case int8:
value := strconv.FormatInt(int64(typed), 10)
if strings.HasPrefix(value, "-") {
return "-" + groupDigits(strings.TrimPrefix(value, "-"), groupSeparator), true
}
return groupDigits(value, groupSeparator), true
case int16:
value := strconv.FormatInt(int64(typed), 10)
if strings.HasPrefix(value, "-") {
return "-" + groupDigits(strings.TrimPrefix(value, "-"), groupSeparator), true
}
return groupDigits(value, groupSeparator), true
case int32:
value := strconv.FormatInt(int64(typed), 10)
if strings.HasPrefix(value, "-") {
return "-" + groupDigits(strings.TrimPrefix(value, "-"), groupSeparator), true
}
return groupDigits(value, groupSeparator), true
case int64:
value := strconv.FormatInt(typed, 10)
if strings.HasPrefix(value, "-") {
return "-" + groupDigits(strings.TrimPrefix(value, "-"), groupSeparator), true
}
return groupDigits(value, groupSeparator), true
case uint:
return groupDigits(strconv.FormatUint(uint64(typed), 10), groupSeparator), true
case uint8:
return groupDigits(strconv.FormatUint(uint64(typed), 10), groupSeparator), true
case uint16:
return groupDigits(strconv.FormatUint(uint64(typed), 10), groupSeparator), true
case uint32:
return groupDigits(strconv.FormatUint(uint64(typed), 10), groupSeparator), true
case uint64:
return groupDigits(strconv.FormatUint(typed, 10), groupSeparator), true
case float32:
return formatFloat(float64(typed)), true
case float64:
return formatFloat(typed), true
default:
return "", false
}
}
func formatDateByLang(lang string, value interface{}) (string, bool) {
var date time.Time
switch typed := value.(type) {
case time.Time:
date = typed
case *time.Time:
if typed == nil {
return "", false
}
date = *typed
default:
return "", false
}
layout := "01/02/2006"
switch baseLangTag(lang) {
case "es", "pt", "fr", "de", "it":
layout = "02/01/2006"
}
return date.Format(layout), true
}
func safeObserverCall(fn func()) {
defer func() {
_ = recover()
}()
fn()
}
func (dmc *DefaultMessageCatalog) startObserverWorker() {
if dmc.cfg.Observer == nil || dmc.observerCh != nil {
return
}
dmc.observerCh = make(chan observerEvent, dmc.cfg.ObserverBuffer)
dmc.observerDone = make(chan struct{})
go func() {
defer close(dmc.observerDone)
for evt := range dmc.observerCh {
switch evt.kind {
case observerEventLanguageFallback:
safeObserverCall(func() {
dmc.cfg.Observer.OnLanguageFallback(evt.requested, evt.resolved)
})
case observerEventLanguageMissing:
safeObserverCall(func() {
dmc.cfg.Observer.OnLanguageMissing(evt.lang)
})
case observerEventMessageMissing:
safeObserverCall(func() {
dmc.cfg.Observer.OnMessageMissing(evt.lang, evt.msgKey)
})
case observerEventTemplateIssue:
safeObserverCall(func() {
dmc.cfg.Observer.OnTemplateIssue(evt.lang, evt.msgKey, evt.templateIssue)
})
}
}
}()
}
func (dmc *DefaultMessageCatalog) stopObserverWorker() {
if dmc.observerCh == nil {
return
}
close(dmc.observerCh)
<-dmc.observerDone
dmc.observerCh = nil
dmc.observerDone = nil
}
func (dmc *DefaultMessageCatalog) publishObserverEvent(evt observerEvent) {
if dmc.cfg.Observer == nil || dmc.observerCh == nil {
return
}
defer func() {
if recover() != nil {
dmc.stats.incrementDroppedEvent("observer_closed")
}
}()
select {
case dmc.observerCh <- evt:
default:
dmc.stats.incrementDroppedEvent("observer_queue_full")
}
}
func (dmc *DefaultMessageCatalog) onLanguageFallback(requestedLang string, resolvedLang string) {
dmc.stats.incrementLanguageFallback(requestedLang, resolvedLang)
dmc.publishObserverEvent(observerEvent{
kind: observerEventLanguageFallback,
requested: requestedLang,
resolved: resolvedLang,
})
}
func (dmc *DefaultMessageCatalog) onLanguageMissing(lang string) {
dmc.stats.incrementMissingLanguage(lang)
dmc.publishObserverEvent(observerEvent{
kind: observerEventLanguageMissing,
lang: lang,
})
}
func (dmc *DefaultMessageCatalog) onMessageMissing(lang string, msgKey string) {
dmc.stats.incrementMissingMessage(lang, msgKey)
dmc.publishObserverEvent(observerEvent{
kind: observerEventMessageMissing,
lang: lang,
msgKey: msgKey,
})
}
func (dmc *DefaultMessageCatalog) onTemplateIssue(lang string, msgKey string, issue string) {
dmc.stats.incrementTemplateIssue(lang, msgKey, issue)
dmc.publishObserverEvent(observerEvent{
kind: observerEventTemplateIssue,
lang: lang,
msgKey: msgKey,
templateIssue: issue,
})
}
func (dmc *DefaultMessageCatalog) resolveRequestedLang(ctx context.Context) string {
lang := normalizeLangTag(dmc.cfg.DefaultLanguage)
if lang == "" {
lang = "en"
}
if ctx == nil {
return lang
}
// Keep backward compatibility with callers that used plain string keys.
if langKeyVal := ctx.Value(dmc.cfg.CtxLanguageKey); langKeyVal != nil {
return normalizeLangTag(fmt.Sprintf("%v", langKeyVal))
}
if langKeyVal := ctx.Value(string(dmc.cfg.CtxLanguageKey)); langKeyVal != nil {
return normalizeLangTag(fmt.Sprintf("%v", langKeyVal))
}
return lang
}
func (dmc *DefaultMessageCatalog) resolveLanguage(requestedLang string) (string, bool, bool) {
normalizedRequested := normalizeLangTag(requestedLang)
if normalizedRequested == "" {
normalizedRequested = "en"
}
candidates := make([]string, 0, 6)
seen := map[string]struct{}{}
appendLangIfMissing(&candidates, seen, normalizedRequested)
appendLangIfMissing(&candidates, seen, baseLangTag(normalizedRequested))
for _, lang := range dmc.cfg.FallbackLanguages {
appendLangIfMissing(&candidates, seen, normalizeLangTag(lang))
}
appendLangIfMissing(&candidates, seen, normalizeLangTag(dmc.cfg.DefaultLanguage))
appendLangIfMissing(&candidates, seen, "en")
dmc.mu.RLock()
defer dmc.mu.RUnlock()
for _, candidate := range candidates {
if _, found := dmc.messages[candidate]; found {
return candidate, true, candidate != normalizedRequested
}
}
return normalizedRequested, false, false
}
func (dmc *DefaultMessageCatalog) renderTemplate(lang string, msgKey string, template string, params map[string]interface{}) string {
if !strings.Contains(template, "{{") {
return template
}
if params == nil {
params = map[string]interface{}{}
}
rendered := template
replaceMissing := func(issue string, originalToken string, paramName string) string {
dmc.onTemplateIssue(lang, msgKey, issue)
if dmc.cfg.StrictTemplates {
return "<missing:" + paramName + ">"
}
return originalToken
}
getParam := func(name string) (interface{}, bool) {
v, ok := params[name]
return v, ok
}
rendered = pluralPlaceholderRegex.ReplaceAllStringFunc(rendered, func(token string) string {
paramName, content, ok := parsePluralToken(token)
if !ok {
return token
}
val, ok := getParam(paramName)
if !ok {
return replaceMissing("plural_missing_param_"+paramName, token, paramName)
}
count, ok := pluralCountFromParam(val)
if !ok {
dmc.onTemplateIssue(lang, msgKey, "plural_invalid_param_"+paramName)
return token
}
parts := strings.Split(content, "|")
// Case 1: Legacy binary plural: {{plural:count|singular|plural}}
if len(parts) == 2 && !strings.Contains(parts[0], ":") {
isOne, _ := isPluralOne(val)
if isOne {
return parts[0]
}
return parts[1]
}
// Case 2: Multi-form plural: {{plural:count|one:singular|few:items|many:items|other:items}}
forms := make(map[string]string)
for _, part := range parts {
if idx := strings.Index(part, ":"); idx > 0 {
formName := strings.TrimSpace(part[:idx])
formValue := part[idx+1:]
forms[formName] = formValue
}
}
if len(forms) > 0 {
form := plural.Form(lang, count)
if tpl, ok := forms[form]; ok {
return tpl
}
if tpl, ok := forms["other"]; ok {
return tpl
}
// fallback to first form if no match
return parts[0]
}
return token
})
rendered = numberPlaceholderRegex.ReplaceAllStringFunc(rendered, func(token string) string {
matches := numberPlaceholderRegex.FindStringSubmatch(token)
if len(matches) != 2 {
return token
}
paramName := matches[1]
val, ok := getParam(paramName)
if !ok {
return replaceMissing("number_missing_param_"+paramName, token, paramName)
}
formatted, ok := formatNumberByLang(lang, val)
if !ok {
dmc.onTemplateIssue(lang, msgKey, "number_invalid_param_"+paramName)
return token
}
return formatted
})
rendered = datePlaceholderRegex.ReplaceAllStringFunc(rendered, func(token string) string {
matches := datePlaceholderRegex.FindStringSubmatch(token)
if len(matches) != 2 {
return token
}
paramName := matches[1]
val, ok := getParam(paramName)
if !ok {
return replaceMissing("date_missing_param_"+paramName, token, paramName)
}
formatted, ok := formatDateByLang(lang, val)
if !ok {
dmc.onTemplateIssue(lang, msgKey, "date_invalid_param_"+paramName)
return token
}
return formatted
})
rendered = simplePlaceholderRegex.ReplaceAllStringFunc(rendered, func(token string) string {
matches := simplePlaceholderRegex.FindStringSubmatch(token)
if len(matches) != 2 {
return token
}
paramName := matches[1]
val, ok := getParam(paramName)
if !ok {
return replaceMissing("simple_missing_param_"+paramName, token, paramName)
}
return toString(val)
})
return rendered
}
func (dmc *DefaultMessageCatalog) LoadMessages(lang string, messages []RawMessage) error {
dmc.mu.Lock()
defer dmc.mu.Unlock()
normalizedLang := normalizeLangTag(lang)
if normalizedLang == "" {
return fmt.Errorf("language is required")
}
if dmc.messages == nil {
dmc.messages = map[string]Messages{}
}
if dmc.runtimeMessages == nil {
dmc.runtimeMessages = map[string]map[string]RawMessage{}
}
if _, foundLangMsg := dmc.messages[normalizedLang]; !foundLangMsg {
dmc.messages[normalizedLang] = Messages{
Set: map[string]RawMessage{},
}
}
if _, foundRuntimeLang := dmc.runtimeMessages[normalizedLang]; !foundRuntimeLang {
dmc.runtimeMessages[normalizedLang] = map[string]RawMessage{}
}
langMsgSet := dmc.messages[normalizedLang]
if langMsgSet.Set == nil {
langMsgSet.Set = map[string]RawMessage{}
}
for _, message := range messages {
key := message.Key
if key == "" {
return fmt.Errorf("LoadMessages: message key is required")
}
if !strings.HasPrefix(key, RuntimeKeyPrefix) {
return fmt.Errorf("LoadMessages: key %q must have prefix %q", key, RuntimeKeyPrefix)
}
if !messageKeyRegex.MatchString(key) {
return fmt.Errorf("LoadMessages: invalid key %q", key)
}
if _, foundMsg := langMsgSet.Set[key]; foundMsg {
return fmt.Errorf("message with key %q already exists in message set for language %s", key, normalizedLang)
}
normalizedMessage := RawMessage{
LongTpl: message.LongTpl,
ShortTpl: message.ShortTpl,
Code: message.Code,
ShortForms: message.ShortForms,
LongForms: message.LongForms,
PluralParam: message.PluralParam,
}
langMsgSet.Set[key] = normalizedMessage
dmc.runtimeMessages[normalizedLang][key] = normalizedMessage
}
dmc.messages[normalizedLang] = langMsgSet
return nil
}
func (dmc *DefaultMessageCatalog) GetMessageWithCtx(ctx context.Context, msgKey string, params Params) *Message {
requestedLang := dmc.resolveRequestedLang(ctx)
resolvedLang, foundLangMsg, usedFallback := dmc.resolveLanguage(requestedLang)
if !foundLangMsg {
dmc.onLanguageMissing(requestedLang)
return &Message{
ShortText: fmt.Sprintf(MessageCatalogNotFound, requestedLang, ""),
LongText: fmt.Sprintf(MessageCatalogNotFound, requestedLang, "Please, contact support."),
Code: CodeMissingLanguage,
Key: msgKey,
}
}
if usedFallback {
dmc.onLanguageFallback(requestedLang, resolvedLang)
}
dmc.mu.RLock()
langMsgSet, langExists := dmc.messages[resolvedLang]
if !langExists {
dmc.mu.RUnlock()
dmc.onLanguageMissing(requestedLang)
return &Message{
ShortText: fmt.Sprintf(MessageCatalogNotFound, requestedLang, ""),
LongText: fmt.Sprintf(MessageCatalogNotFound, requestedLang, "Please, contact support."),
Code: CodeMissingLanguage,
Key: msgKey,
}
}
shortMessage := langMsgSet.Default.ShortTpl
longMessage := langMsgSet.Default.LongTpl
code := CodeMissingMessage
missingMessage := false
if msg, ok := langMsgSet.Set[msgKey]; ok {
shortMessage = msg.ShortTpl
longMessage = msg.LongTpl
code = string(msg.Code)
// CLDR plural forms: when ShortForms/LongForms are set, select by plural param and language
if len(msg.ShortForms) > 0 || len(msg.LongForms) > 0 {
pluralParam := msg.PluralParam
if pluralParam == "" {
pluralParam = "count"
}
paramMap := map[string]interface{}(params)
if paramMap == nil {
paramMap = map[string]interface{}{}
}
if countVal, ok := pluralCountFromParam(paramMap[pluralParam]); ok {
shortMessage = selectCLDRForm(msg.ShortForms, resolvedLang, countVal, shortMessage)
longMessage = selectCLDRForm(msg.LongForms, resolvedLang, countVal, longMessage)
}
}
} else {
missingMessage = true
}
dmc.mu.RUnlock()
if missingMessage {
dmc.onMessageMissing(resolvedLang, msgKey)
}
paramMap := map[string]interface{}(params)
if paramMap == nil {
paramMap = map[string]interface{}{}
}
shortMessage = dmc.renderTemplate(resolvedLang, msgKey, shortMessage, paramMap)
longMessage = dmc.renderTemplate(resolvedLang, msgKey, longMessage, paramMap)
return &Message{
LongText: longMessage,
ShortText: shortMessage,
Code: code,
Key: msgKey,
}
}
func (dmc *DefaultMessageCatalog) WrapErrorWithCtx(ctx context.Context, err error, msgKey string, params Params) error {
message := dmc.GetMessageWithCtx(ctx, msgKey, params)
return newCatalogError(message.Code, message.Key, message.ShortText, message.LongText, err)
}
func (dmc *DefaultMessageCatalog) GetErrorWithCtx(ctx context.Context, msgKey string, params Params) error {
return dmc.WrapErrorWithCtx(ctx, nil, msgKey, params)
}
func (dmc *DefaultMessageCatalog) Reload() error {
return dmc.loadFromYaml()
}
func (dmc *DefaultMessageCatalog) SnapshotStats() MessageCatalogStats {
return dmc.stats.snapshot()
}
func (dmc *DefaultMessageCatalog) ResetStats() {
dmc.stats.reset()
}
func (dmc *DefaultMessageCatalog) Close() {
dmc.mu.Lock()
defer dmc.mu.Unlock()
dmc.stopObserverWorker()
}
func Reload(catalog MessageCatalog) error {
reloadable, ok := catalog.(interface{ Reload() error })
if !ok {
return fmt.Errorf("catalog does not support reload")
}
return reloadable.Reload()
}
func SnapshotStats(catalog MessageCatalog) (MessageCatalogStats, error) {
statsProvider, ok := catalog.(interface{ SnapshotStats() MessageCatalogStats })
if !ok {
return MessageCatalogStats{}, fmt.Errorf("catalog does not support stats snapshots")
}
return statsProvider.SnapshotStats(), nil
}