Build and Deploy / test-backend (push) Successful in 1m11s
Build and Deploy / lint-frontend (push) Successful in 21s
Build and Deploy / build-backend (push) Successful in 58s
Build and Deploy / deploy (push) Canceled after 0s
Build and Deploy / build-frontend (push) Canceled after 5m38s
68 lines
1.8 KiB
Go
68 lines
1.8 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"log"
|
|
"time"
|
|
|
|
"github.com/dusiburg/fancy-api/internal/model"
|
|
"github.com/dusiburg/fancy-api/internal/provider/translation"
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
const redisCacheTTL = 30 * 24 * time.Hour
|
|
|
|
type TranslationService struct {
|
|
provider translation.Provider
|
|
redis *redis.Client
|
|
}
|
|
|
|
func NewTranslationService(provider translation.Provider, r *redis.Client) *TranslationService {
|
|
return &TranslationService{provider: provider, redis: r}
|
|
}
|
|
|
|
func (s *TranslationService) Translate(ctx context.Context, text string, from, to model.Language) (*model.TranslationResult, error) {
|
|
key := translationCacheKey(text, from, to)
|
|
|
|
val, err := s.redis.Get(ctx, key).Result()
|
|
if err != nil && !errors.Is(err, redis.Nil) {
|
|
log.Printf("getting key %q: %v", key, err)
|
|
}
|
|
|
|
if err == nil {
|
|
var result model.TranslationResult
|
|
if err := json.Unmarshal([]byte(val), &result); err != nil {
|
|
log.Printf("unmarshaling cached result for %q: %v", key, err)
|
|
} else {
|
|
result.Source = model.Cache
|
|
return &result, nil
|
|
}
|
|
}
|
|
|
|
result, err := s.provider.Translate(ctx, text, from, to)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("translate %q [%s>%s]: %w", text, from, to, err)
|
|
}
|
|
result.Source = model.Provider
|
|
generatedAt := time.Now().UTC()
|
|
result.GeneratedAt = &generatedAt
|
|
|
|
if data, err := json.Marshal(result); err != nil {
|
|
log.Printf("marshaling translation for cache %q: %v", key, err)
|
|
} else if err := s.redis.Set(ctx, key, data, redisCacheTTL).Err(); err != nil {
|
|
log.Printf("caching translation %q: %v", key, err)
|
|
}
|
|
|
|
return result, nil
|
|
}
|
|
|
|
func translationCacheKey(text string, from, to model.Language) string {
|
|
sum := sha256.Sum256([]byte(text))
|
|
return fmt.Sprintf("translate:%s:%s:%s", from, to, hex.EncodeToString(sum[:]))
|
|
}
|