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
+43
View File
@@ -0,0 +1,43 @@
package service
import (
"context"
"github.com/google/uuid"
"github.com/dusiburg/fancy-api/internal/model"
"github.com/dusiburg/fancy-api/internal/provider/kotosoft"
"github.com/dusiburg/fancy-api/internal/repository"
)
type AuthService struct {
kotosoft *kotosoft.Client
users *repository.UserRepository
sessions *SessionService
}
func NewAuthService(kotosoft *kotosoft.Client, users *repository.UserRepository, sessions *SessionService) *AuthService {
return &AuthService{kotosoft: kotosoft, users: users, sessions: sessions}
}
func (s *AuthService) CreateSession(ctx context.Context, accessToken string) (string, error) {
profile, err := s.kotosoft.GetUserInfo(ctx, accessToken)
if err != nil {
return "", ErrKotosoftUnauthorized
}
user, err := s.users.UpsertByKotosoftID(ctx, profile.ID, profile.Email, profile.FirstName, profile.SecondName)
if err != nil {
return "", err
}
return s.sessions.Create(ctx, user.Id)
}
func (s *AuthService) GetUser(ctx context.Context, userID uuid.UUID) (*model.User, error) {
return s.users.GetByID(ctx, userID)
}
func (s *AuthService) RevokeSession(ctx context.Context, token string) error {
return s.sessions.Revoke(ctx, token)
}
@@ -0,0 +1,131 @@
package service
import (
"context"
"slices"
"github.com/dusiburg/fancy-api/internal/model"
"github.com/dusiburg/fancy-api/internal/repository"
"github.com/google/uuid"
)
type CollectionService struct {
repository *repository.CollectionRepository
}
func NewCollectionService(repository *repository.CollectionRepository) *CollectionService {
return &CollectionService{repository: repository}
}
func (s *CollectionService) getOwned(ctx context.Context, userID, collectionID uuid.UUID) (*model.Collection, error) {
existing, err := s.repository.GetCollectionByID(ctx, collectionID)
if err != nil {
return nil, err
}
if existing.UserID != userID {
return nil, ErrCollectionNotOwned
}
return existing, nil
}
func (s *CollectionService) getOwnedEditable(ctx context.Context, userID, collectionID uuid.UUID) (*model.Collection, error) {
existing, err := s.getOwned(ctx, userID, collectionID)
if err != nil {
return nil, err
}
if existing.Type == model.CollectionTypeAuto {
return nil, ErrCollectionNotOwned
}
return existing, nil
}
func (s *CollectionService) GetCollections(ctx context.Context, userID uuid.UUID) ([]model.Collection, error) {
return s.repository.GetCollections(ctx, userID)
}
func (s *CollectionService) GetCollectionByID(ctx context.Context, userID, collectionID uuid.UUID) (*model.Collection, error) {
return s.getOwned(ctx, userID, collectionID)
}
func (s *CollectionService) GetCollectionsByWord(ctx context.Context, userID uuid.UUID, lang model.Language, word string) ([]model.Collection, error) {
return s.repository.GetCollectionsByWord(ctx, userID, lang, word)
}
func (s *CollectionService) CreateCollection(ctx context.Context, userID uuid.UUID, name string, lang model.Language) (*model.Collection, error) {
c := &model.Collection{
Name: name,
Lang: lang,
UserID: userID,
Type: model.CollectionTypeUser,
Words: []string{},
}
return s.repository.CreateCollection(ctx, c)
}
func (s *CollectionService) UpdateCollectionDetails(ctx context.Context, userID, collectionID uuid.UUID, name string) (*model.Collection, error) {
existing, err := s.getOwnedEditable(ctx, userID, collectionID)
if err != nil {
return nil, err
}
existing.Name = name
return s.repository.UpdateCollection(ctx, existing)
}
func (s *CollectionService) AddWords(ctx context.Context, userID, collectionID uuid.UUID, words []string) (*model.Collection, error) {
existing, err := s.getOwnedEditable(ctx, userID, collectionID)
if err != nil {
return nil, err
}
for _, word := range words {
if !slices.Contains(existing.Words, word) {
existing.Words = append(existing.Words, word)
}
}
return s.repository.UpdateCollection(ctx, existing)
}
func (s *CollectionService) DeleteWord(ctx context.Context, userID, id uuid.UUID, word string) (*model.Collection, error) {
existing, err := s.getOwnedEditable(ctx, userID, id)
if err != nil {
return nil, err
}
idx := slices.Index(existing.Words, word)
if idx == -1 {
return nil, ErrWordNotFound
}
existing.Words = slices.Delete(existing.Words, idx, idx+1)
return s.repository.UpdateCollection(ctx, existing)
}
func (s *CollectionService) AppendToHistory(ctx context.Context, userID uuid.UUID, lang model.Language, word string) error {
existing, err := s.repository.GetOrCreateAutoCollection(ctx, userID, lang)
if err != nil {
return err
}
if slices.Contains(existing.Words, word) {
return nil
}
existing.Words = append(existing.Words, word)
_, err = s.repository.UpdateCollection(ctx, existing)
return err
}
func (s *CollectionService) DeleteCollection(ctx context.Context, userID, id uuid.UUID) error {
if _, err := s.getOwnedEditable(ctx, userID, id); err != nil {
return err
}
return s.repository.DeleteCollection(ctx, id)
}
@@ -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[:]))
}
@@ -0,0 +1,81 @@
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/dictionary"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
)
type DictionaryService struct {
provider dictionary.Provider
redis *redis.Client
collections *CollectionService
}
func NewDictionaryService(provider dictionary.Provider, r *redis.Client, collections *CollectionService) *DictionaryService {
return &DictionaryService{provider: provider, redis: r, collections: collections}
}
func (s *DictionaryService) Lookup(ctx context.Context, userID uuid.UUID, word string, lang model.Language) (*model.DictionaryResult, error) {
key := dictionaryCacheKey(word, lang)
ctx = WithUserID(ctx, userID)
result, err := s.lookupResult(ctx, key, word, lang)
if err != nil {
return nil, err
}
if err := s.collections.AppendToHistory(ctx, userID, lang, word); err != nil {
log.Printf("appending %q to history for user %s: %v", word, userID, err)
}
return result, nil
}
func (s *DictionaryService) lookupResult(ctx context.Context, key, word string, lang model.Language) (*model.DictionaryResult, error) {
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 cached model.DictionaryResult
if err := json.Unmarshal([]byte(val), &cached); err != nil {
log.Printf("unmarshaling cached result for %q: %v", key, err)
} else {
cached.Source = model.Cache
return &cached, nil
}
}
result, err := s.provider.Lookup(ctx, word, lang)
if err != nil {
return nil, fmt.Errorf("lookup %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 dictionary for cache %q: %v", key, err)
} else if err := s.redis.Set(ctx, key, data, redisCacheTTL).Err(); err != nil {
log.Printf("caching dictionary %q: %v", key, err)
}
return result, nil
}
func dictionaryCacheKey(word string, lang model.Language) string {
sum := sha256.Sum256([]byte(word))
return fmt.Sprintf("dictionary:%s:%s:%s", word, lang, hex.EncodeToString(sum[:]))
}
+10
View File
@@ -0,0 +1,10 @@
package service
import "errors"
var (
ErrWordNotFound = errors.New("word not found")
ErrWordExists = errors.New("word already exists in collection")
ErrCollectionNotOwned = errors.New("you cannot delete this collection")
ErrKotosoftUnauthorized = errors.New("kotosoft: invalid access token")
)
@@ -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/examples"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
)
type ExamplesService struct {
provider examples.Provider
redis *redis.Client
}
func NewExamplesService(provider examples.Provider, r *redis.Client) *ExamplesService {
return &ExamplesService{provider: provider, redis: r}
}
func (s *ExamplesService) GenerateExamples(ctx context.Context, userID uuid.UUID, word string, lang model.Language) (*model.ExamplesResult, error) {
key := examplesCacheKey(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.ExamplesResult
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.GenerateExamples(ctx, word, lang)
if err != nil {
return nil, fmt.Errorf("generating examples 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 examples for cache %q: %v", key, err)
} else if err := s.redis.Set(ctx, key, data, 0).Err(); err != nil {
log.Printf("caching examples %q: %v", key, err)
}
return result, nil
}
func examplesCacheKey(word string, lang model.Language) string {
sum := sha256.Sum256([]byte(word))
return fmt.Sprintf("examples:%s:%s:%s", word, lang, hex.EncodeToString(sum[:]))
}
+151
View File
@@ -0,0 +1,151 @@
package service
import (
"context"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
)
// SessionService issues signed, expiring session JWTs and keeps an index in
// Redis so that sessions can be revoked (e.g. on logout).
type SessionService struct {
redis *redis.Client
secret []byte
ttl time.Duration
}
func NewSessionService(redis *redis.Client, secret string) *SessionService {
return &SessionService{redis: redis, secret: []byte(secret), ttl: 30 * 24 * time.Hour}
}
type sessionClaims struct {
Sub string `json:"sub"`
JTI string `json:"jti"`
Iat int64 `json:"iat"`
Exp int64 `json:"exp"`
}
func (s *SessionService) Create(ctx context.Context, userID uuid.UUID) (string, error) {
jtiBytes := make([]byte, 16)
if _, err := rand.Read(jtiBytes); err != nil {
return "", err
}
jti := hex.EncodeToString(jtiBytes)
now := time.Now().UTC()
claims := sessionClaims{
Sub: userID.String(),
JTI: jti,
Iat: now.Unix(),
Exp: now.Add(s.ttl).Unix(),
}
token, err := signToken(claims, s.secret)
if err != nil {
return "", err
}
if err := s.redis.Set(ctx, "session:"+jti, userID.String(), s.ttl).Err(); err != nil {
return "", err
}
return token, nil
}
func (s *SessionService) UserID(ctx context.Context, token string) (string, error) {
claims, err := parseToken(token, s.secret)
if err != nil {
return "", err
}
stored, err := s.redis.Get(ctx, "session:"+claims.JTI).Result()
if err != nil {
if errors.Is(err, redis.Nil) {
return "", fmt.Errorf("session revoked or expired")
}
return "", err
}
if stored != claims.Sub {
return "", fmt.Errorf("session token mismatch")
}
return stored, nil
}
func (s *SessionService) Revoke(ctx context.Context, token string) error {
claims, err := parseToken(token, s.secret)
if err != nil {
return err
}
if err := s.redis.Del(ctx, "session:"+claims.JTI).Err(); err != nil {
return err
}
return nil
}
func signToken(claims sessionClaims, secret []byte) (string, error) {
header := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"HS256","typ":"JWT"}`))
payload, err := json.Marshal(claims)
if err != nil {
return "", err
}
payloadB64 := base64.RawURLEncoding.EncodeToString(payload)
signingInput := header + "." + payloadB64
mac := hmac.New(sha256.New, secret)
mac.Write([]byte(signingInput))
signature := base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
return signingInput + "." + signature, nil
}
func parseToken(token string, secret []byte) (*sessionClaims, error) {
parts := strings.Split(token, ".")
if len(parts) != 3 {
return nil, errors.New("malformed token")
}
signature, err := base64.RawURLEncoding.DecodeString(parts[2])
if err != nil {
return nil, fmt.Errorf("invalid token signature encoding: %w", err)
}
mac := hmac.New(sha256.New, secret)
mac.Write([]byte(parts[0] + "." + parts[1]))
if !hmac.Equal(signature, mac.Sum(nil)) {
return nil, errors.New("invalid token signature")
}
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return nil, fmt.Errorf("invalid token payload encoding: %w", err)
}
var claims sessionClaims
if err := json.Unmarshal(payload, &claims); err != nil {
return nil, fmt.Errorf("invalid token payload: %w", err)
}
if claims.Sub == "" || claims.JTI == "" {
return nil, errors.New("token missing claims")
}
if claims.Exp < time.Now().UTC().Unix() {
return nil, errors.New("token expired")
}
return &claims, nil
}
@@ -0,0 +1,67 @@
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[:]))
}
+136
View File
@@ -0,0 +1,136 @@
package service
import (
"context"
"errors"
"fmt"
"log"
"strconv"
"time"
"github.com/dusiburg/fancy-api/internal/model"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
)
const aiUsageTTL = 45 * 24 * time.Hour
type userIDContextKey struct{}
func WithUserID(ctx context.Context, id uuid.UUID) context.Context {
return context.WithValue(ctx, userIDContextKey{}, id)
}
func userIDFromContext(ctx context.Context) (uuid.UUID, bool) {
id, ok := ctx.Value(userIDContextKey{}).(uuid.UUID)
return id, ok
}
type UsageTracker struct {
redis *redis.Client
}
func NewUsageTracker(r *redis.Client) *UsageTracker {
return &UsageTracker{redis: r}
}
func (t *UsageTracker) RecordAIUsage(ctx context.Context, tokens int64) {
month := time.Now().UTC().Format("2006-01")
pipe := t.redis.Pipeline()
pipe.Incr(ctx, fmt.Sprintf("usage:ai:requests:%s", month))
pipe.IncrBy(ctx, fmt.Sprintf("usage:ai:tokens:%s", month), tokens)
pipe.Expire(ctx, fmt.Sprintf("usage:ai:requests:%s", month), aiUsageTTL)
pipe.Expire(ctx, fmt.Sprintf("usage:ai:tokens:%s", month), aiUsageTTL)
if userID, ok := userIDFromContext(ctx); ok {
uid := userID.String()
pipe.Incr(ctx, fmt.Sprintf("usage:ai:requests:%s:%s", uid, month))
pipe.IncrBy(ctx, fmt.Sprintf("usage:ai:tokens:%s:%s", uid, month), tokens)
pipe.SAdd(ctx, fmt.Sprintf("usage:ai:users:%s", month), uid)
pipe.Expire(ctx, fmt.Sprintf("usage:ai:requests:%s:%s", uid, month), aiUsageTTL)
pipe.Expire(ctx, fmt.Sprintf("usage:ai:tokens:%s:%s", uid, month), aiUsageTTL)
pipe.Expire(ctx, fmt.Sprintf("usage:ai:users:%s", month), aiUsageTTL)
}
if _, err := pipe.Exec(ctx); err != nil {
log.Printf("recording ai usage: %v", err)
}
}
func (t *UsageTracker) AIUsage(ctx context.Context, userID uuid.UUID) (*model.AIUsage, error) {
month := time.Now().UTC().Format("2006-01")
uid := userID.String()
pipe := t.redis.Pipeline()
requestsCmd := pipe.Get(ctx, fmt.Sprintf("usage:ai:requests:%s:%s", uid, month))
tokensCmd := pipe.Get(ctx, fmt.Sprintf("usage:ai:tokens:%s:%s", uid, month))
if _, err := pipe.Exec(ctx); err != nil && !errors.Is(err, redis.Nil) {
return nil, fmt.Errorf("getting ai usage keys: %w", err)
}
usage := &model.AIUsage{}
usage.Requests = atoi64(requestsCmd.Val())
usage.Tokens = atoi64(tokensCmd.Val())
return usage, nil
}
func (t *UsageTracker) ActiveUsers(ctx context.Context) int64 {
month := time.Now().UTC().Format("2006-01")
count, err := t.redis.SCard(ctx, fmt.Sprintf("usage:ai:users:%s", month)).Result()
if err != nil {
log.Printf("counting active users: %v", err)
return 0
}
return count
}
func atoi64(val string) int64 {
n, err := strconv.ParseInt(val, 10, 64)
if err != nil {
return 0
}
return n
}
type DeepLUsageReporter interface {
Usage(ctx context.Context) (*model.DeepLUsage, error)
}
type UsageService struct {
tracker *UsageTracker
deepl DeepLUsageReporter
tokenLimit int64
}
func NewUsageService(tracker *UsageTracker, deepl DeepLUsageReporter, tokenLimit int64) *UsageService {
return &UsageService{tracker: tracker, deepl: deepl, tokenLimit: tokenLimit}
}
func (s *UsageService) GetUsage(ctx context.Context, userID uuid.UUID) (*model.UsageResult, error) {
ai, err := s.tracker.AIUsage(ctx, userID)
if err != nil {
log.Printf("getting ai usage: %v", err)
ai = &model.AIUsage{}
}
users := s.tracker.ActiveUsers(ctx)
if users < 1 {
users = 1
}
ai.TokenLimit = s.tokenLimit / users
result := &model.UsageResult{AI: ai}
if deepL, err := s.deepl.Usage(ctx); err != nil {
log.Printf("getting deepl usage: %v", err)
} else {
deepL.CharacterLimit = deepL.CharacterLimit / users
result.DeepL = deepL
}
return result, nil
}