version 1
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

This commit is contained in:
Ivan Rezchikov
2026-09-18 00:45:51 +03:00
commit 628dd6384b
149 changed files with 11478 additions and 0 deletions
@@ -0,0 +1,66 @@
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/collocations"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
)
type CollocationsService struct {
provider collocations.Provider
redis *redis.Client
}
func NewCollocationsService(provider collocations.Provider, r *redis.Client) *CollocationsService {
return &CollocationsService{provider: provider, redis: r}
}
func (s *CollocationsService) GenerateCollocations(ctx context.Context, userID uuid.UUID, word string, lang model.Language) (*model.CollocationsResult, error) {
key := collocationsCacheKey(word, lang)
ctx = WithUserID(ctx, userID)
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.CollocationsResult
if err := json.Unmarshal([]byte(val), &result); err != nil {
log.Printf("unmarshaling cached result for %q: %v", key, err)
}
result.Source = model.Cache
return &result, nil
}
result, err := s.provider.GenerateCollocations(ctx, word, lang)
if err != nil {
return nil, fmt.Errorf("generating collocations for %q [%s]: %w", word, lang, err)
}
result.Source = model.Provider
generatedAt := time.Now().UTC()
result.GeneratedAt = &generatedAt
if data, err := json.Marshal(result); err != nil {
log.Printf("marshaling collocations for cache %q: %v", key, err)
} else if err := s.redis.Set(ctx, key, data, 0).Err(); err != nil {
log.Printf("caching collocations %q: %v", key, err)
}
return result, nil
}
func collocationsCacheKey(word string, lang model.Language) string {
sum := sha256.Sum256([]byte(word))
return fmt.Sprintf("collocations:%s:%s:%s", word, lang, hex.EncodeToString(sum[:]))
}