Add production hardening: monitoring, backups, caching, and high-traffic resilience

- Recovery middleware (no more crash-on-panic), request metrics/monitoring
  store + admin API, in-memory TTL caching for read-heavy option/question/
  category lookups, gzip + rate-limiting middleware, sanitized chat message
  encoding, and pg_dump-based database backups with an admin API.
- Fix N+1 queries in the discover feed, candidate detail, and match list
  endpoints by batching selection/photo/user/last-message lookups into
  single queries instead of one-per-item loops.
- Tune DB connection pooling and add HTTP server timeouts + graceful
  shutdown so the API degrades gracefully instead of falling over under load.
- Fix a null (vs empty array) JSON response for candidates/matches without
  photos or interests, which crashed the web app's swipe card.
This commit is contained in:
2026-09-19 22:17:12 +03:30
parent 15583009e0
commit 769e76313f
29 changed files with 1377 additions and 72 deletions
+69 -42
View File
@@ -134,33 +134,37 @@ func (s *DiscoveryService) GetFeed(user *models.User, maxDistanceKM *float64, mi
result := make([]dto.DiscoverCandidate, 0, len(withDist))
for _, wd := range withDist {
result = append(result, dto.DiscoverCandidate{
ID: wd.user.ID,
FirstName: wd.user.FirstName,
Age: utils.CalcAge(wd.user.BirthDate),
Photos: photosByUser[wd.user.ID],
ID: wd.user.ID,
FirstName: wd.user.FirstName,
Age: utils.CalcAge(wd.user.BirthDate),
// نبود عکس/علاقه‌مندی نباید توی JSON به‌صورت null دربیاد؛ کلاینت‌ها
// همیشه یک آرایه (حتی خالی) انتظار دارن، نه null.
Photos: orEmptyStrings(photosByUser[wd.user.ID]),
DistanceKM: wd.distance,
Interests: interestsByUser[wd.user.ID],
Interests: orEmptyStrings(interestsByUser[wd.user.ID]),
})
}
return result, nil
}
func orEmptyStrings(s []string) []string {
if s == nil {
return []string{}
}
return s
}
// batchInterests علاقه‌مندی‌های تمام کاندیداهای فید رو در یک کوئری واحد
// می‌گیره (به‌جای یک کوئری جدا به‌ازای هر کاندیدا)؛ روی فید دیسکاوری که تا ۶۰
// کاربر با هم پردازش می‌شن، این تفاوت بین ۱ کوئری و تا ۶۰ کوئری رو ایجاد می‌کنه.
func (s *DiscoveryService) batchInterests(userIDs []uint) map[uint][]string {
result := map[uint][]string{}
cat, err := s.optionRepo.GetCategoryByKey(models.CategoryInterest)
if err != nil {
return result
return map[uint][]string{}
}
for _, id := range userIDs {
sels, err := s.optionRepo.GetUserSelections(id, cat.ID)
if err != nil {
continue
}
for _, sel := range sels {
if sel.Option != nil {
result[id] = append(result[id], sel.Option.Title)
}
}
result, err := s.optionRepo.GetSelectionsForUsersInCategory(userIDs, cat.ID)
if err != nil {
return map[uint][]string{}
}
return result
}
@@ -254,12 +258,26 @@ func (s *DiscoveryService) GetCandidateDetail(viewer *models.User, targetID uint
WeightKG: target.WeightKG,
}
detail.Education = s.firstSelectionTitle(target.ID, models.CategoryEducationLevel)
detail.FieldOfStudy = s.firstSelectionTitle(target.ID, models.CategoryFieldOfStudy)
detail.LookingFor = s.firstSelectionTitle(target.ID, models.CategoryLookingFor)
detail.Occupations = s.allSelectionTitles(target.ID, models.CategoryOccupation)
detail.Interests = s.allSelectionTitles(target.ID, models.CategoryInterest)
detail.ImportantInRelationship = s.allSelectionTitles(target.ID, models.CategoryImportantInRelationship)
titlesByCategory := s.selectionTitlesByCategory(target.ID, []models.CategoryKey{
models.CategoryEducationLevel,
models.CategoryFieldOfStudy,
models.CategoryLookingFor,
models.CategoryOccupation,
models.CategoryInterest,
models.CategoryImportantInRelationship,
})
first := func(titles []string) string {
if len(titles) == 0 {
return ""
}
return titles[0]
}
detail.Education = first(titlesByCategory[models.CategoryEducationLevel])
detail.FieldOfStudy = first(titlesByCategory[models.CategoryFieldOfStudy])
detail.LookingFor = first(titlesByCategory[models.CategoryLookingFor])
detail.Occupations = titlesByCategory[models.CategoryOccupation]
detail.Interests = titlesByCategory[models.CategoryInterest]
detail.ImportantInRelationship = titlesByCategory[models.CategoryImportantInRelationship]
if answers, err := s.questionRepo.GetUserAnswers(target.ID); err == nil {
for _, a := range answers {
@@ -276,28 +294,37 @@ func (s *DiscoveryService) GetCandidateDetail(viewer *models.User, targetID uint
return detail, nil
}
func (s *DiscoveryService) allSelectionTitles(userID uint, key models.CategoryKey) []string {
cat, err := s.optionRepo.GetCategoryByKey(key)
if err != nil {
return nil
// selectionTitlesByCategory انتخاب‌های یک کاربر رو در چند دسته با هم، طی یک
// کوئری واحد به دیتابیس می‌گیره (به‌جای یک کوئری جدا به‌ازای هر دسته که قبلاً
// برای صفحه‌ی جزئیات پروفایل تا ۶ رفت‌وبرگشت جدا به دیتابیس می‌زد).
// GetCategoryByKey از کش می‌خونه (چون دسته‌ها به‌ندرت تغییر می‌کنن) پس عملاً
// فقط همین یک کوئری واقعی به دیتابیس زده می‌شه.
func (s *DiscoveryService) selectionTitlesByCategory(userID uint, keys []models.CategoryKey) map[models.CategoryKey][]string {
result := make(map[models.CategoryKey][]string, len(keys))
categoryIDToKey := make(map[uint]models.CategoryKey, len(keys))
categoryIDs := make([]uint, 0, len(keys))
for _, key := range keys {
cat, err := s.optionRepo.GetCategoryByKey(key)
if err != nil {
continue
}
categoryIDToKey[cat.ID] = key
categoryIDs = append(categoryIDs, cat.ID)
}
sels, err := s.optionRepo.GetUserSelections(userID, cat.ID)
selectionsByCategoryID, err := s.optionRepo.GetUserSelectionsForCategories(userID, categoryIDs)
if err != nil {
return nil
return result
}
titles := make([]string, 0, len(sels))
for _, sel := range sels {
if sel.Option != nil {
titles = append(titles, sel.Option.Title)
for categoryID, sels := range selectionsByCategoryID {
key := categoryIDToKey[categoryID]
for _, sel := range sels {
if sel.Option != nil {
result[key] = append(result[key], sel.Option.Title)
}
}
}
return titles
}
func (s *DiscoveryService) firstSelectionTitle(userID uint, key models.CategoryKey) string {
titles := s.allSelectionTitles(userID, key)
if len(titles) == 0 {
return ""
}
return titles[0]
return result
}