From eb1d0c68e284803317f2a8d147a407c49278f4c3 Mon Sep 17 00:00:00 2001 From: Yared Yemane Date: Sat, 1 Aug 2026 00:06:43 -0700 Subject: [PATCH] Speed up API paths with batch question loads, request memoization, and soft caches. Also replace question options on update so placement grading stays consistent with admin edits, and tune the Postgres pool defaults. Co-authored-by: Cursor --- db/query/question_options.sql | 6 + db/query/question_short_answers.sql | 6 + gen/db/models.go | 7 + gen/db/question_options.sql.go | 34 ++++ gen/db/question_short_answers.sql.go | 33 ++++ internal/ports/questions.go | 1 + internal/repository/questions.go | 146 ++++++++++++++---- internal/repository/store.go | 51 ++++-- .../services/assessment/initial_assessment.go | 16 +- internal/services/assessment/placement.go | 12 +- internal/services/lmsprogress/request_memo.go | 89 +++++++++++ internal/services/lmsprogress/service.go | 96 ++++++++++++ .../services/practicecontent/question_sync.go | 10 +- internal/services/practicecontent/service.go | 14 +- internal/services/questions/catalog_cache.go | 49 ++++++ internal/services/questions/service.go | 30 ++-- internal/services/subscriptions/service.go | 74 ++++++++- internal/services/user/auth_status_cache.go | 73 +++++++++ internal/services/user/direct.go | 20 ++- internal/services/user/service.go | 1 + .../handlers/admin_user_detail_handler.go | 7 +- .../web_server/handlers/course_handler.go | 4 +- .../web_server/handlers/lesson_handler.go | 4 +- .../handlers/lms_progress_handler.go | 7 +- .../web_server/handlers/module_handler.go | 4 +- .../web_server/handlers/program_handler.go | 4 +- internal/web_server/handlers/questions.go | 45 ++++-- internal/web_server/middleware.go | 17 +- 28 files changed, 754 insertions(+), 106 deletions(-) create mode 100644 internal/services/lmsprogress/request_memo.go create mode 100644 internal/services/questions/catalog_cache.go create mode 100644 internal/services/user/auth_status_cache.go diff --git a/db/query/question_options.sql b/db/query/question_options.sql index 2cb0a63b..1b3dd3e1 100644 --- a/db/query/question_options.sql +++ b/db/query/question_options.sql @@ -14,6 +14,12 @@ FROM question_options WHERE question_id = $1 ORDER BY option_order; +-- name: GetOptionsByQuestionIDs :many +SELECT * +FROM question_options +WHERE question_id = ANY($1::BIGINT[]) +ORDER BY question_id, option_order; + -- name: UpdateQuestionOption :exec UPDATE question_options SET diff --git a/db/query/question_short_answers.sql b/db/query/question_short_answers.sql index 6141fe89..8fb18805 100644 --- a/db/query/question_short_answers.sql +++ b/db/query/question_short_answers.sql @@ -12,6 +12,12 @@ SELECT * FROM question_short_answers WHERE question_id = $1; +-- name: GetShortAnswersByQuestionIDs :many +SELECT * +FROM question_short_answers +WHERE question_id = ANY($1::BIGINT[]) +ORDER BY question_id, id; + -- name: UpdateQuestionShortAnswer :exec UPDATE question_short_answers SET diff --git a/gen/db/models.go b/gen/db/models.go index a201aff1..41c8462f 100644 --- a/gen/db/models.go +++ b/gen/db/models.go @@ -164,6 +164,13 @@ type GlobalSetting struct { UpdatedAt pgtype.Timestamptz `json:"updated_at"` } +type InitialAssessmentLevelThreshold struct { + Level string `json:"level"` + MinPercent int32 `json:"min_percent"` + DisplayOrder int32 `json:"display_order"` + UpdatedAt pgtype.Timestamptz `json:"updated_at"` +} + type Lesson struct { ID int64 `json:"id"` ModuleID int64 `json:"module_id"` diff --git a/gen/db/question_options.sql.go b/gen/db/question_options.sql.go index c82c2564..ea0c7857 100644 --- a/gen/db/question_options.sql.go +++ b/gen/db/question_options.sql.go @@ -107,6 +107,40 @@ func (q *Queries) GetOptionsByQuestionID(ctx context.Context, questionID int64) return items, nil } +const GetOptionsByQuestionIDs = `-- name: GetOptionsByQuestionIDs :many +SELECT id, question_id, option_text, option_order, is_correct, created_at +FROM question_options +WHERE question_id = ANY($1::BIGINT[]) +ORDER BY question_id, option_order +` + +func (q *Queries) GetOptionsByQuestionIDs(ctx context.Context, dollar_1 []int64) ([]QuestionOption, error) { + rows, err := q.db.Query(ctx, GetOptionsByQuestionIDs, dollar_1) + if err != nil { + return nil, err + } + defer rows.Close() + var items []QuestionOption + for rows.Next() { + var i QuestionOption + if err := rows.Scan( + &i.ID, + &i.QuestionID, + &i.OptionText, + &i.OptionOrder, + &i.IsCorrect, + &i.CreatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const UpdateQuestionOption = `-- name: UpdateQuestionOption :exec UPDATE question_options SET diff --git a/gen/db/question_short_answers.sql.go b/gen/db/question_short_answers.sql.go index ce2df7b7..1b397260 100644 --- a/gen/db/question_short_answers.sql.go +++ b/gen/db/question_short_answers.sql.go @@ -90,6 +90,39 @@ func (q *Queries) GetShortAnswersByQuestionID(ctx context.Context, questionID in return items, nil } +const GetShortAnswersByQuestionIDs = `-- name: GetShortAnswersByQuestionIDs :many +SELECT id, question_id, acceptable_answer, match_type, created_at +FROM question_short_answers +WHERE question_id = ANY($1::BIGINT[]) +ORDER BY question_id, id +` + +func (q *Queries) GetShortAnswersByQuestionIDs(ctx context.Context, dollar_1 []int64) ([]QuestionShortAnswer, error) { + rows, err := q.db.Query(ctx, GetShortAnswersByQuestionIDs, dollar_1) + if err != nil { + return nil, err + } + defer rows.Close() + var items []QuestionShortAnswer + for rows.Next() { + var i QuestionShortAnswer + if err := rows.Scan( + &i.ID, + &i.QuestionID, + &i.AcceptableAnswer, + &i.MatchType, + &i.CreatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const UpdateQuestionShortAnswer = `-- name: UpdateQuestionShortAnswer :exec UPDATE question_short_answers SET diff --git a/internal/ports/questions.go b/internal/ports/questions.go index 75b81b20..6e0a6d6b 100644 --- a/internal/ports/questions.go +++ b/internal/ports/questions.go @@ -25,6 +25,7 @@ type QuestionStore interface { CreateQuestion(ctx context.Context, input domain.CreateQuestionInput) (domain.Question, error) GetQuestionByID(ctx context.Context, id int64) (domain.Question, error) GetQuestionWithDetails(ctx context.Context, id int64) (domain.QuestionWithDetails, error) + GetQuestionsWithDetailsByIDs(ctx context.Context, ids []int64) (map[int64]domain.QuestionWithDetails, error) ListQuestions(ctx context.Context, questionType, difficulty, status *string, limit, offset int32) ([]domain.Question, int64, error) SearchQuestions(ctx context.Context, query string, limit, offset int32) ([]domain.Question, int64, error) UpdateQuestion(ctx context.Context, id int64, input domain.CreateQuestionInput) error diff --git a/internal/repository/questions.go b/internal/repository/questions.go index 6b9b0e29..3379e75f 100644 --- a/internal/repository/questions.go +++ b/internal/repository/questions.go @@ -653,44 +653,83 @@ func (s *Store) GetQuestionByID(ctx context.Context, id int64) (domain.Question, } func (s *Store) GetQuestionWithDetails(ctx context.Context, id int64) (domain.QuestionWithDetails, error) { - q, err := s.queries.GetQuestionByID(ctx, id) + byID, err := s.GetQuestionsWithDetailsByIDs(ctx, []int64{id}) if err != nil { return domain.QuestionWithDetails{}, err } + qwd, ok := byID[id] + if !ok { + return domain.QuestionWithDetails{}, pgx.ErrNoRows + } + return qwd, nil +} - opts, err := s.queries.GetOptionsByQuestionID(ctx, id) +// GetQuestionsWithDetailsByIDs loads questions plus options, short answers, and audio answers +// in a constant number of queries (instead of ~4 queries per question). +func (s *Store) GetQuestionsWithDetailsByIDs(ctx context.Context, ids []int64) (map[int64]domain.QuestionWithDetails, error) { + out := make(map[int64]domain.QuestionWithDetails, len(ids)) + if len(ids) == 0 { + return out, nil + } + + unique := make([]int64, 0, len(ids)) + seen := make(map[int64]struct{}, len(ids)) + for _, id := range ids { + if id <= 0 { + continue + } + if _, ok := seen[id]; ok { + continue + } + seen[id] = struct{}{} + unique = append(unique, id) + } + if len(unique) == 0 { + return out, nil + } + + questions, err := s.queries.GetQuestionsByIDs(ctx, unique) if err != nil { - return domain.QuestionWithDetails{}, err + return nil, err } - shortAnswers, err := s.queries.GetShortAnswersByQuestionID(ctx, id) + opts, err := s.queries.GetOptionsByQuestionIDs(ctx, unique) if err != nil { - return domain.QuestionWithDetails{}, err + return nil, err + } + shortAnswers, err := s.queries.GetShortAnswersByQuestionIDs(ctx, unique) + if err != nil { + return nil, err + } + audioAnswers, err := s.queries.GetAudioAnswersByQuestionIDs(ctx, unique) + if err != nil { + return nil, err } - options := make([]domain.QuestionOption, len(opts)) - for i, o := range opts { - options[i] = questionOptionToDomain(o) + optionsByQ := make(map[int64][]domain.QuestionOption, len(unique)) + for _, o := range opts { + optionsByQ[o.QuestionID] = append(optionsByQ[o.QuestionID], questionOptionToDomain(o)) + } + shortByQ := make(map[int64][]domain.QuestionShortAnswer, len(unique)) + for _, a := range shortAnswers { + shortByQ[a.QuestionID] = append(shortByQ[a.QuestionID], questionShortAnswerToDomain(a)) + } + audioByQ := make(map[int64]*domain.QuestionAudioAnswer, len(audioAnswers)) + for _, a := range audioAnswers { + mapped := questionAudioAnswerToDomain(a) + audioByQ[a.QuestionID] = &mapped } - answers := make([]domain.QuestionShortAnswer, len(shortAnswers)) - for i, a := range shortAnswers { - answers[i] = questionShortAnswerToDomain(a) + for _, q := range questions { + qid := q.ID + out[qid] = domain.QuestionWithDetails{ + Question: questionToDomain(q), + Options: optionsByQ[qid], + ShortAnswers: shortByQ[qid], + AudioAnswer: audioByQ[qid], + } } - - var audioAnswer *domain.QuestionAudioAnswer - aa, err := s.queries.GetAudioAnswerByQuestionID(ctx, id) - if err == nil { - mapped := questionAudioAnswerToDomain(aa) - audioAnswer = &mapped - } - - return domain.QuestionWithDetails{ - Question: questionToDomain(q), - Options: options, - ShortAnswers: answers, - AudioAnswer: audioAnswer, - }, nil + return out, nil } func (s *Store) ListQuestions(ctx context.Context, questionType, difficulty, status *string, limit, offset int32) ([]domain.Question, int64, error) { @@ -783,6 +822,12 @@ func (s *Store) SearchQuestions(ctx context.Context, query string, limit, offset } func (s *Store) UpdateQuestion(ctx context.Context, id int64, input domain.CreateQuestionInput) error { + q, tx, err := s.BeginTx(ctx) + if err != nil { + return err + } + defer tx.Rollback(ctx) + var points int32 if input.Points != nil { points = *input.Points @@ -792,7 +837,7 @@ func (s *Store) UpdateQuestion(ctx context.Context, id int64, input domain.Creat status = *input.Status } - err := s.queries.UpdateQuestion(ctx, dbgen.UpdateQuestionParams{ + err = q.UpdateQuestion(ctx, dbgen.UpdateQuestionParams{ ID: id, QuestionText: input.QuestionText, QuestionType: input.QuestionType, @@ -810,10 +855,51 @@ func (s *Store) UpdateQuestion(ctx context.Context, id int64, input domain.Creat return err } + if input.Options != nil { + if err := q.DeleteOptionsByQuestionID(ctx, id); err != nil { + return err + } + for _, opt := range input.Options { + var order interface{} + if opt.OptionOrder != nil { + order = *opt.OptionOrder + } + _, err = q.CreateQuestionOption(ctx, dbgen.CreateQuestionOptionParams{ + QuestionID: id, + OptionText: opt.OptionText, + Column3: order, + Column4: opt.IsCorrect, + }) + if err != nil { + return err + } + } + } + + if input.ShortAnswers != nil { + if err := q.DeleteShortAnswersByQuestionID(ctx, id); err != nil { + return err + } + for _, sa := range input.ShortAnswers { + var matchType interface{} + if sa.MatchType != nil { + matchType = *sa.MatchType + } + _, err = q.CreateQuestionShortAnswer(ctx, dbgen.CreateQuestionShortAnswerParams{ + QuestionID: id, + AcceptableAnswer: sa.AcceptableAnswer, + Column3: matchType, + }) + if err != nil { + return err + } + } + } + if input.AudioCorrectAnswerText != nil { - _ = s.queries.DeleteAudioAnswerByQuestionID(ctx, id) + _ = q.DeleteAudioAnswerByQuestionID(ctx, id) if *input.AudioCorrectAnswerText != "" { - _, err = s.queries.CreateQuestionAudioAnswer(ctx, dbgen.CreateQuestionAudioAnswerParams{ + _, err = q.CreateQuestionAudioAnswer(ctx, dbgen.CreateQuestionAudioAnswerParams{ QuestionID: id, CorrectAnswerText: *input.AudioCorrectAnswerText, }) @@ -824,12 +910,12 @@ func (s *Store) UpdateQuestion(ctx context.Context, id int64, input domain.Creat } if input.QuestionTypeDefinitionID != nil { - if err := s.setQuestionTypeDefinitionID(ctx, s.conn, id, input.QuestionTypeDefinitionID); err != nil { + if err := s.setQuestionTypeDefinitionID(ctx, tx, id, input.QuestionTypeDefinitionID); err != nil { return err } } - return nil + return tx.Commit(ctx) } func (s *Store) ArchiveQuestion(ctx context.Context, id int64) error { diff --git a/internal/repository/store.go b/internal/repository/store.go index 1c1cef47..edc5927f 100644 --- a/internal/repository/store.go +++ b/internal/repository/store.go @@ -2,13 +2,14 @@ package repository import ( "context" + "os" + "strconv" "time" dbgen "Yimaru-Backend/gen/db" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" - // "golang.org/x/net/websocket" ) type Store struct { @@ -29,12 +30,25 @@ func OpenDB(url string) (*pgxpool.Pool, func(), error) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - conn, err := pgxpool.New(ctx, url) + cfg, err := pgxpool.ParseConfig(url) + if err != nil { + return nil, func() {}, err + } + + // Sensible production defaults; override via env without changing DB_URL query params. + cfg.MaxConns = envInt32("DB_MAX_CONNS", 25) + cfg.MinConns = envInt32("DB_MIN_CONNS", 5) + cfg.MaxConnLifetime = time.Duration(envInt64("DB_MAX_CONN_LIFETIME_MINUTES", 30)) * time.Minute + cfg.MaxConnIdleTime = time.Duration(envInt64("DB_MAX_CONN_IDLE_MINUTES", 5)) * time.Minute + cfg.HealthCheckPeriod = time.Duration(envInt64("DB_HEALTH_CHECK_SECONDS", 30)) * time.Second + + conn, err := pgxpool.NewWithConfig(ctx, cfg) if err != nil { return nil, func() {}, err } if err := conn.Ping(ctx); err != nil { + conn.Close() return nil, func() {}, err } @@ -43,6 +57,30 @@ func OpenDB(url string) (*pgxpool.Pool, func(), error) { }, nil } +func envInt32(key string, fallback int32) int32 { + raw := os.Getenv(key) + if raw == "" { + return fallback + } + n, err := strconv.Atoi(raw) + if err != nil || n <= 0 { + return fallback + } + return int32(n) +} + +func envInt64(key string, fallback int64) int64 { + raw := os.Getenv(key) + if raw == "" { + return fallback + } + n, err := strconv.ParseInt(raw, 10, 64) + if err != nil || n <= 0 { + return fallback + } + return n +} + func (s *Store) BeginTx(ctx context.Context) (*dbgen.Queries, pgx.Tx, error) { tx, err := s.conn.Begin(ctx) if err != nil { @@ -51,12 +89,3 @@ func (s *Store) BeginTx(ctx context.Context) (*dbgen.Queries, pgx.Tx, error) { q := s.queries.WithTx(tx) return q, tx, nil } - -// func (s *Store) ConnectWebSocket(ctx context.Context, recipientID int64, c *websocket.Conn) error { -// // Implement WebSocket connection logic -// return nil -// } - -// func (s *Store) DisconnectWebSocket(recipientID int64) { -// // Implement WebSocket disconnection logic -// } diff --git a/internal/services/assessment/initial_assessment.go b/internal/services/assessment/initial_assessment.go index fd62e70e..7ccf8ccd 100644 --- a/internal/services/assessment/initial_assessment.go +++ b/internal/services/assessment/initial_assessment.go @@ -29,12 +29,20 @@ func (s *Service) ListQuestions(ctx context.Context) ([]domain.QuestionWithDetai return nil, err } - // Build the full question details + ids := make([]int64, 0, len(items)) + for _, item := range items { + ids = append(ids, item.QuestionID) + } + byID, err := s.questionStore.GetQuestionsWithDetailsByIDs(ctx, ids) + if err != nil { + return nil, err + } + result := make([]domain.QuestionWithDetails, 0, len(items)) for _, item := range items { - qwd, err := s.questionStore.GetQuestionWithDetails(ctx, item.QuestionID) - if err != nil { - continue // Skip if we can't get details + qwd, ok := byID[item.QuestionID] + if !ok { + continue } result = append(result, qwd) } diff --git a/internal/services/assessment/placement.go b/internal/services/assessment/placement.go index 079812d7..c2f3214f 100644 --- a/internal/services/assessment/placement.go +++ b/internal/services/assessment/placement.go @@ -56,9 +56,17 @@ func (s *Service) SubmitPlacement(ctx context.Context, userID int64, answers []d } questions := make([]domain.QuestionWithDetails, 0, len(items)) + ids := make([]int64, 0, len(items)) for _, item := range items { - qwd, err := s.questionStore.GetQuestionWithDetails(ctx, item.QuestionID) - if err != nil { + ids = append(ids, item.QuestionID) + } + byID, err := s.questionStore.GetQuestionsWithDetailsByIDs(ctx, ids) + if err != nil { + return domain.PlacementAssessmentResult{}, err + } + for _, item := range items { + qwd, ok := byID[item.QuestionID] + if !ok { continue } questions = append(questions, qwd) diff --git a/internal/services/lmsprogress/request_memo.go b/internal/services/lmsprogress/request_memo.go new file mode 100644 index 00000000..7cfd8471 --- /dev/null +++ b/internal/services/lmsprogress/request_memo.go @@ -0,0 +1,89 @@ +package lmsprogress + +import ( + "context" + "sync" +) + +type progressMemoKey struct { + kind string + userID int64 + id int64 +} + +type progressMemoVal struct { + fraction float64 + done bool + completed int32 + total int32 + err error +} + +type accessMemoVal struct { + ok bool + reason string + err error +} + +// requestMemo caches LMS/exam-prep access and progress calculations within a single request. +type requestMemo struct { + mu sync.Mutex + access map[progressMemoKey]accessMemoVal + progress map[progressMemoKey]progressMemoVal +} + +type requestMemoCtxKey struct{} + +// WithRequestMemo attaches a per-request memoization cache used by access/progress helpers. +func WithRequestMemo(ctx context.Context) context.Context { + if memoFrom(ctx) != nil { + return ctx + } + return context.WithValue(ctx, requestMemoCtxKey{}, &requestMemo{ + access: make(map[progressMemoKey]accessMemoVal), + progress: make(map[progressMemoKey]progressMemoVal), + }) +} + +func memoFrom(ctx context.Context) *requestMemo { + v, _ := ctx.Value(requestMemoCtxKey{}).(*requestMemo) + return v +} + +func (m *requestMemo) getAccess(kind string, userID, id int64) (accessMemoVal, bool) { + if m == nil { + return accessMemoVal{}, false + } + m.mu.Lock() + defer m.mu.Unlock() + v, ok := m.access[progressMemoKey{kind: kind, userID: userID, id: id}] + return v, ok +} + +func (m *requestMemo) setAccess(kind string, userID, id int64, v accessMemoVal) { + if m == nil { + return + } + m.mu.Lock() + m.access[progressMemoKey{kind: kind, userID: userID, id: id}] = v + m.mu.Unlock() +} + +func (m *requestMemo) getProgress(kind string, userID, id int64) (progressMemoVal, bool) { + if m == nil { + return progressMemoVal{}, false + } + m.mu.Lock() + defer m.mu.Unlock() + v, ok := m.progress[progressMemoKey{kind: kind, userID: userID, id: id}] + return v, ok +} + +func (m *requestMemo) setProgress(kind string, userID, id int64, v progressMemoVal) { + if m == nil { + return + } + m.mu.Lock() + m.progress[progressMemoKey{kind: kind, userID: userID, id: id}] = v + m.mu.Unlock() +} diff --git a/internal/services/lmsprogress/service.go b/internal/services/lmsprogress/service.go index 88035f09..3a9989e2 100644 --- a/internal/services/lmsprogress/service.go +++ b/internal/services/lmsprogress/service.go @@ -50,6 +50,12 @@ func (s *Service) GetMyProgress(ctx context.Context, userID int64) (domain.LMSUs // CanAccessProgram returns whether the user may use content under this program (previous program must be fully completed if any). func (s *Service) CanAccessProgram(ctx context.Context, userID, programID int64) (ok bool, reason string, err error) { + if v, hit := memoFrom(ctx).getAccess("program", userID, programID); hit { + return v.ok, v.reason, v.err + } + defer func() { + memoFrom(ctx).setAccess("program", userID, programID, accessMemoVal{ok: ok, reason: reason, err: err}) + }() if _, err := s.store.GetProgramByID(ctx, programID); err != nil { return false, "", err } @@ -72,6 +78,12 @@ func (s *Service) CanAccessProgram(ctx context.Context, userID, programID int64) // CanAccessCourse requires the parent program to be accessible and the previous course in the program to be completed. func (s *Service) CanAccessCourse(ctx context.Context, userID, courseID int64) (ok bool, reason string, err error) { + if v, hit := memoFrom(ctx).getAccess("course", userID, courseID); hit { + return v.ok, v.reason, v.err + } + defer func() { + memoFrom(ctx).setAccess("course", userID, courseID, accessMemoVal{ok: ok, reason: reason, err: err}) + }() c, err := s.store.GetCourseByID(ctx, courseID) if err != nil { return false, "", err @@ -99,6 +111,12 @@ func (s *Service) CanAccessCourse(ctx context.Context, userID, courseID int64) ( // CanAccessModule requires the course (and its program chain) to be accessible and the previous module in the course to be completed. func (s *Service) CanAccessModule(ctx context.Context, userID, moduleID int64) (ok bool, reason string, err error) { + if v, hit := memoFrom(ctx).getAccess("module", userID, moduleID); hit { + return v.ok, v.reason, v.err + } + defer func() { + memoFrom(ctx).setAccess("module", userID, moduleID, accessMemoVal{ok: ok, reason: reason, err: err}) + }() m, err := s.store.GetModuleByID(ctx, moduleID) if err != nil { return false, "", err @@ -127,6 +145,12 @@ func (s *Service) CanAccessModule(ctx context.Context, userID, moduleID int64) ( // CanAccessLesson requires the module chain to be accessible and the previous lesson in the module // to be completed based on published practice completion in that lesson. func (s *Service) CanAccessLesson(ctx context.Context, userID, lessonID int64) (ok bool, reason string, err error) { + if v, hit := memoFrom(ctx).getAccess("lesson", userID, lessonID); hit { + return v.ok, v.reason, v.err + } + defer func() { + memoFrom(ctx).setAccess("lesson", userID, lessonID, accessMemoVal{ok: ok, reason: reason, err: err}) + }() lesson, err := s.store.GetLessonByID(ctx, lessonID) if err != nil { return false, "", err @@ -156,6 +180,12 @@ func (s *Service) CanAccessLesson(ctx context.Context, userID, lessonID int64) ( // CanAccessExamPrepCatalogCourse returns whether the user may use content under this catalog course. func (s *Service) CanAccessExamPrepCatalogCourse(ctx context.Context, userID, catalogCourseID int64) (ok bool, reason string, err error) { + if v, hit := memoFrom(ctx).getAccess("ep_catalog", userID, catalogCourseID); hit { + return v.ok, v.reason, v.err + } + defer func() { + memoFrom(ctx).setAccess("ep_catalog", userID, catalogCourseID, accessMemoVal{ok: ok, reason: reason, err: err}) + }() if _, err := s.store.GetExamPrepCatalogCourseByID(ctx, catalogCourseID); err != nil { return false, "", err } @@ -178,6 +208,12 @@ func (s *Service) CanAccessExamPrepCatalogCourse(ctx context.Context, userID, ca // CanAccessExamPrepUnit requires the parent catalog course chain and the previous unit to be completed. func (s *Service) CanAccessExamPrepUnit(ctx context.Context, userID, unitID int64) (ok bool, reason string, err error) { + if v, hit := memoFrom(ctx).getAccess("ep_unit", userID, unitID); hit { + return v.ok, v.reason, v.err + } + defer func() { + memoFrom(ctx).setAccess("ep_unit", userID, unitID, accessMemoVal{ok: ok, reason: reason, err: err}) + }() u, err := s.store.GetExamPrepUnitByID(ctx, unitID) if err != nil { return false, "", err @@ -205,6 +241,12 @@ func (s *Service) CanAccessExamPrepUnit(ctx context.Context, userID, unitID int6 // CanAccessExamPrepModule requires the unit chain and the previous module in the unit to be completed. func (s *Service) CanAccessExamPrepModule(ctx context.Context, userID, moduleID int64) (ok bool, reason string, err error) { + if v, hit := memoFrom(ctx).getAccess("ep_module", userID, moduleID); hit { + return v.ok, v.reason, v.err + } + defer func() { + memoFrom(ctx).setAccess("ep_module", userID, moduleID, accessMemoVal{ok: ok, reason: reason, err: err}) + }() m, err := s.store.GetExamPrepUnitModuleByID(ctx, moduleID) if err != nil { return false, "", err @@ -232,6 +274,12 @@ func (s *Service) CanAccessExamPrepModule(ctx context.Context, userID, moduleID // CanAccessExamPrepLesson requires the module chain and the previous lesson's practices to be completed. func (s *Service) CanAccessExamPrepLesson(ctx context.Context, userID, lessonID int64) (ok bool, reason string, err error) { + if v, hit := memoFrom(ctx).getAccess("ep_lesson", userID, lessonID); hit { + return v.ok, v.reason, v.err + } + defer func() { + memoFrom(ctx).setAccess("ep_lesson", userID, lessonID, accessMemoVal{ok: ok, reason: reason, err: err}) + }() lesson, err := s.store.GetExamPrepUnitModuleLessonByID(ctx, lessonID) if err != nil { return false, "", err @@ -509,6 +557,12 @@ func (s *Service) ApplyExamPrepAccessLesson(ctx context.Context, role domain.Rol } func (s *Service) lmsLessonProgress(ctx context.Context, userID, lessonID int64) (fraction float64, done bool, completed, total int32, err error) { + if v, hit := memoFrom(ctx).getProgress("lms_lesson", userID, lessonID); hit { + return v.fraction, v.done, v.completed, v.total, v.err + } + defer func() { + memoFrom(ctx).setProgress("lms_lesson", userID, lessonID, progressMemoVal{fraction: fraction, done: done, completed: completed, total: total, err: err}) + }() completed, total, err = s.store.LmsUserPracticeProgressInLesson(ctx, userID, lessonID) if err != nil { return 0, false, 0, 0, err @@ -521,6 +575,12 @@ func (s *Service) lmsLessonProgress(ctx context.Context, userID, lessonID int64) } func (s *Service) lmsModuleProgress(ctx context.Context, userID, moduleID int64) (fraction float64, done bool, completed, total int32, err error) { + if v, hit := memoFrom(ctx).getProgress("lms_module", userID, moduleID); hit { + return v.fraction, v.done, v.completed, v.total, v.err + } + defer func() { + memoFrom(ctx).setProgress("lms_module", userID, moduleID, progressMemoVal{fraction: fraction, done: done, completed: completed, total: total, err: err}) + }() directDone, directErr := s.hasCompletedDirectModulePractice(ctx, userID, moduleID) if directErr != nil { return 0, false, 0, 0, directErr @@ -556,6 +616,12 @@ func (s *Service) lmsModuleProgress(ctx context.Context, userID, moduleID int64) } func (s *Service) lmsCourseProgress(ctx context.Context, userID, courseID int64) (fraction float64, done bool, completed, total int32, err error) { + if v, hit := memoFrom(ctx).getProgress("lms_course", userID, courseID); hit { + return v.fraction, v.done, v.completed, v.total, v.err + } + defer func() { + memoFrom(ctx).setProgress("lms_course", userID, courseID, progressMemoVal{fraction: fraction, done: done, completed: completed, total: total, err: err}) + }() directDone, directErr := s.hasCompletedDirectCoursePractice(ctx, userID, courseID) if directErr != nil { return 0, false, 0, 0, directErr @@ -592,6 +658,12 @@ func (s *Service) lmsCourseProgress(ctx context.Context, userID, courseID int64) } func (s *Service) lmsProgramProgress(ctx context.Context, userID, programID int64) (fraction float64, done bool, completed, total int32, err error) { + if v, hit := memoFrom(ctx).getProgress("lms_program", userID, programID); hit { + return v.fraction, v.done, v.completed, v.total, v.err + } + defer func() { + memoFrom(ctx).setProgress("lms_program", userID, programID, progressMemoVal{fraction: fraction, done: done, completed: completed, total: total, err: err}) + }() courseIDs, err := s.store.ListPublishedCourseIDsByProgram(ctx, programID) if err != nil { return 0, false, 0, 0, err @@ -636,6 +708,12 @@ func (s *Service) hasCompletedDirectCoursePractice(ctx context.Context, userID, } func (s *Service) examPrepLessonProgress(ctx context.Context, userID, lessonID int64) (fraction float64, done bool, completed, total int32, err error) { + if v, hit := memoFrom(ctx).getProgress("ep_lesson_prog", userID, lessonID); hit { + return v.fraction, v.done, v.completed, v.total, v.err + } + defer func() { + memoFrom(ctx).setProgress("ep_lesson_prog", userID, lessonID, progressMemoVal{fraction: fraction, done: done, completed: completed, total: total, err: err}) + }() completed, total, err = s.store.ExamPrepUserPracticeProgressInLesson(ctx, userID, lessonID) if err != nil { return 0, false, 0, 0, err @@ -647,6 +725,12 @@ func (s *Service) examPrepLessonProgress(ctx context.Context, userID, lessonID i } func (s *Service) examPrepModuleProgress(ctx context.Context, userID, moduleID int64) (fraction float64, done bool, completed, total int32, err error) { + if v, hit := memoFrom(ctx).getProgress("ep_module_prog", userID, moduleID); hit { + return v.fraction, v.done, v.completed, v.total, v.err + } + defer func() { + memoFrom(ctx).setProgress("ep_module_prog", userID, moduleID, progressMemoVal{fraction: fraction, done: done, completed: completed, total: total, err: err}) + }() lessonIDs, err := s.store.ListPublishedExamPrepUnitModuleLessonIDsByUnitModule(ctx, moduleID) if err != nil { return 0, false, 0, 0, err @@ -691,6 +775,12 @@ func (s *Service) hasCompletedDirectCatalogCoursePractice(ctx context.Context, u } func (s *Service) examPrepUnitProgress(ctx context.Context, userID, unitID int64) (fraction float64, done bool, completed, total int32, err error) { + if v, hit := memoFrom(ctx).getProgress("ep_unit_prog", userID, unitID); hit { + return v.fraction, v.done, v.completed, v.total, v.err + } + defer func() { + memoFrom(ctx).setProgress("ep_unit_prog", userID, unitID, progressMemoVal{fraction: fraction, done: done, completed: completed, total: total, err: err}) + }() directDone, directErr := s.hasCompletedDirectUnitPractice(ctx, userID, unitID) if directErr != nil { return 0, false, 0, 0, directErr @@ -727,6 +817,12 @@ func (s *Service) examPrepUnitProgress(ctx context.Context, userID, unitID int64 } func (s *Service) examPrepCatalogCourseProgress(ctx context.Context, userID, catalogCourseID int64) (fraction float64, done bool, completed, total int32, err error) { + if v, hit := memoFrom(ctx).getProgress("ep_catalog_prog", userID, catalogCourseID); hit { + return v.fraction, v.done, v.completed, v.total, v.err + } + defer func() { + memoFrom(ctx).setProgress("ep_catalog_prog", userID, catalogCourseID, progressMemoVal{fraction: fraction, done: done, completed: completed, total: total, err: err}) + }() directDone, directErr := s.hasCompletedDirectCatalogCoursePractice(ctx, userID, catalogCourseID) if directErr != nil { return 0, false, 0, 0, directErr diff --git a/internal/services/practicecontent/question_sync.go b/internal/services/practicecontent/question_sync.go index aa3d1214..85833795 100644 --- a/internal/services/practicecontent/question_sync.go +++ b/internal/services/practicecontent/question_sync.go @@ -359,10 +359,14 @@ func (s *Service) syncQuestionsInSet( } out := make([]domain.QuestionWithDetails, 0, len(orderedIDs)) + byID, err := s.questions.GetQuestionsWithDetailsByIDs(ctx, orderedIDs) + if err != nil { + return nil, err + } for _, id := range orderedIDs { - q, err := s.questions.GetQuestionWithDetails(ctx, id) - if err != nil { - return nil, err + q, ok := byID[id] + if !ok { + return nil, fmt.Errorf("question %d not found", id) } out = append(out, q) } diff --git a/internal/services/practicecontent/service.go b/internal/services/practicecontent/service.go index c7b98ae8..041df72f 100644 --- a/internal/services/practicecontent/service.go +++ b/internal/services/practicecontent/service.go @@ -154,11 +154,19 @@ func (s *Service) loadQuestionsInSet(ctx context.Context, questionSetID int64) ( if err != nil { return nil, nil, err } + ids := make([]int64, 0, len(items)) + for _, item := range items { + ids = append(ids, item.QuestionID) + } + byID, err := s.questions.GetQuestionsWithDetailsByIDs(ctx, ids) + if err != nil { + return nil, nil, err + } questions := make([]domain.QuestionWithDetails, 0, len(items)) for _, item := range items { - q, err := s.questions.GetQuestionWithDetails(ctx, item.QuestionID) - if err != nil { - return nil, nil, err + q, ok := byID[item.QuestionID] + if !ok { + return nil, nil, pgx.ErrNoRows } questions = append(questions, q) } diff --git a/internal/services/questions/catalog_cache.go b/internal/services/questions/catalog_cache.go new file mode 100644 index 00000000..7a47eb56 --- /dev/null +++ b/internal/services/questions/catalog_cache.go @@ -0,0 +1,49 @@ +package questions + +import ( + "Yimaru-Backend/internal/domain" + "context" + "sync" + "time" +) + +const activeCatalogTTL = 2 * time.Minute + +type activeCatalogCache struct { + mu sync.RWMutex + defs []domain.QuestionTypeDefinition + expiresAt time.Time +} + +func (s *Service) invalidateActiveCatalogCache() { + s.catalogCache.mu.Lock() + s.catalogCache.defs = nil + s.catalogCache.expiresAt = time.Time{} + s.catalogCache.mu.Unlock() +} + +func (s *Service) ActiveQuestionTypeDefinitionCatalog(ctx context.Context) ([]domain.QuestionTypeDefinition, error) { + now := time.Now() + s.catalogCache.mu.RLock() + if len(s.catalogCache.defs) > 0 && now.Before(s.catalogCache.expiresAt) { + out := append([]domain.QuestionTypeDefinition(nil), s.catalogCache.defs...) + s.catalogCache.mu.RUnlock() + return out, nil + } + s.catalogCache.mu.RUnlock() + + s.catalogCache.mu.Lock() + defer s.catalogCache.mu.Unlock() + if len(s.catalogCache.defs) > 0 && time.Now().Before(s.catalogCache.expiresAt) { + return append([]domain.QuestionTypeDefinition(nil), s.catalogCache.defs...), nil + } + + active := "ACTIVE" + catalog, _, err := s.questionStore.ListQuestionTypeDefinitions(ctx, &active, true, nil, 0, 0) + if err != nil { + return nil, err + } + s.catalogCache.defs = catalog + s.catalogCache.expiresAt = time.Now().Add(activeCatalogTTL) + return append([]domain.QuestionTypeDefinition(nil), catalog...), nil +} diff --git a/internal/services/questions/service.go b/internal/services/questions/service.go index ee91c54b..e6c8f84b 100644 --- a/internal/services/questions/service.go +++ b/internal/services/questions/service.go @@ -9,6 +9,7 @@ import ( type Service struct { questionStore ports.QuestionStore + catalogCache activeCatalogCache } func NewService(questionStore ports.QuestionStore) *Service { @@ -20,7 +21,12 @@ func NewService(questionStore ports.QuestionStore) *Service { // Question Type Definitions (dynamic builder presets) func (s *Service) CreateQuestionTypeDefinition(ctx context.Context, input domain.CreateQuestionTypeDefinitionInput) (domain.QuestionTypeDefinition, error) { - return s.questionStore.CreateQuestionTypeDefinition(ctx, input) + def, err := s.questionStore.CreateQuestionTypeDefinition(ctx, input) + if err != nil { + return domain.QuestionTypeDefinition{}, err + } + s.invalidateActiveCatalogCache() + return def, nil } func (s *Service) GetQuestionTypeDefinitionByID(ctx context.Context, id int64) (domain.QuestionTypeDefinition, error) { @@ -45,18 +51,20 @@ func (s *Service) ListQuestionTypeDefinitions(ctx context.Context, status *strin return s.questionStore.ListQuestionTypeDefinitions(ctx, status, includeSystem, groupID, limit, offset) } -func (s *Service) ActiveQuestionTypeDefinitionCatalog(ctx context.Context) ([]domain.QuestionTypeDefinition, error) { - active := "ACTIVE" - catalog, _, err := s.questionStore.ListQuestionTypeDefinitions(ctx, &active, true, nil, 0, 0) - return catalog, err -} - func (s *Service) UpdateQuestionTypeDefinition(ctx context.Context, id int64, input domain.UpdateQuestionTypeDefinitionInput) error { - return s.questionStore.UpdateQuestionTypeDefinition(ctx, id, input) + if err := s.questionStore.UpdateQuestionTypeDefinition(ctx, id, input); err != nil { + return err + } + s.invalidateActiveCatalogCache() + return nil } func (s *Service) DeleteQuestionTypeDefinition(ctx context.Context, id int64) error { - return s.questionStore.DeleteQuestionTypeDefinition(ctx, id) + if err := s.questionStore.DeleteQuestionTypeDefinition(ctx, id); err != nil { + return err + } + s.invalidateActiveCatalogCache() + return nil } func (s *Service) CreateQuestionTypeDefinitionGroup(ctx context.Context, input domain.CreateQuestionTypeDefinitionGroupInput) (domain.QuestionTypeDefinitionGroup, error) { @@ -98,6 +106,10 @@ func (s *Service) GetQuestionWithDetails(ctx context.Context, id int64) (domain. return s.questionStore.GetQuestionWithDetails(ctx, id) } +func (s *Service) GetQuestionsWithDetailsByIDs(ctx context.Context, ids []int64) (map[int64]domain.QuestionWithDetails, error) { + return s.questionStore.GetQuestionsWithDetailsByIDs(ctx, ids) +} + func (s *Service) ListQuestions(ctx context.Context, questionType, difficulty, status *string, limit, offset int32) ([]domain.Question, int64, error) { return s.questionStore.ListQuestions(ctx, questionType, difficulty, status, limit, offset) } diff --git a/internal/services/subscriptions/service.go b/internal/services/subscriptions/service.go index 324d8002..e96af074 100644 --- a/internal/services/subscriptions/service.go +++ b/internal/services/subscriptions/service.go @@ -7,6 +7,7 @@ import ( "context" "errors" "fmt" + "sync" "time" "github.com/jackc/pgx/v5" @@ -26,10 +27,29 @@ var ( type Service struct { store ports.SubscriptionStore payments ports.PaymentStore + + activeByCategoryMu sync.RWMutex + activeByCategory map[subscriptionActiveKey]subscriptionActiveEntry } +type subscriptionActiveKey struct { + userID int64 + category domain.SubscriptionCategory +} + +type subscriptionActiveEntry struct { + active bool + expiresAt time.Time +} + +const subscriptionActiveCacheTTL = 30 * time.Second + func NewService(store ports.SubscriptionStore, payments ports.PaymentStore) *Service { - return &Service{store: store, payments: payments} + return &Service{ + store: store, + payments: payments, + activeByCategory: make(map[subscriptionActiveKey]subscriptionActiveEntry), + } } // ===================== @@ -111,7 +131,12 @@ func (s *Service) Subscribe(ctx context.Context, userID, planID int64, paymentRe AutoRenew: boolPtr(false), } - return s.store.CreateUserSubscription(ctx, input) + sub, err := s.store.CreateUserSubscription(ctx, input) + if err != nil { + return nil, err + } + s.invalidateActiveSubscriptionCache(userID) + return sub, nil } // AdminGrantSubscription assigns a plan to a learner (admin panel). @@ -162,6 +187,7 @@ func (s *Service) createAdminGrantedSubscription(ctx context.Context, userID int if err := s.recordAdminPayment(ctx, sub, plan, method, note); err != nil { return nil, err } + s.invalidateActiveSubscriptionCache(userID) return s.GetSubscriptionByID(ctx, sub.ID) } @@ -220,6 +246,7 @@ func (s *Service) AdminApplySubscription(ctx context.Context, userID, planID int if err := s.recordAdminPayment(ctx, updated, plan, "ADMIN_EXTEND", ¬e); err != nil { return nil, err } + s.invalidateActiveSubscriptionCache(userID) return &domain.AdminApplySubscriptionResult{Subscription: updated, Created: false}, nil } @@ -267,7 +294,37 @@ func (s *Service) HasActiveSubscription(ctx context.Context, userID int64) (bool } func (s *Service) HasActiveSubscriptionByCategory(ctx context.Context, userID int64, category domain.SubscriptionCategory) (bool, error) { - return s.store.HasActiveSubscriptionByCategory(ctx, userID, string(category)) + key := subscriptionActiveKey{userID: userID, category: category} + s.activeByCategoryMu.RLock() + if entry, ok := s.activeByCategory[key]; ok && time.Now().Before(entry.expiresAt) { + active := entry.active + s.activeByCategoryMu.RUnlock() + return active, nil + } + s.activeByCategoryMu.RUnlock() + + active, err := s.store.HasActiveSubscriptionByCategory(ctx, userID, string(category)) + if err != nil { + return false, err + } + + s.activeByCategoryMu.Lock() + s.activeByCategory[key] = subscriptionActiveEntry{ + active: active, + expiresAt: time.Now().Add(subscriptionActiveCacheTTL), + } + s.activeByCategoryMu.Unlock() + return active, nil +} + +func (s *Service) invalidateActiveSubscriptionCache(userID int64) { + s.activeByCategoryMu.Lock() + for key := range s.activeByCategory { + if key.userID == userID { + delete(s.activeByCategory, key) + } + } + s.activeByCategoryMu.Unlock() } func (s *Service) subscriptionOwnedBy(ctx context.Context, subscriptionID, userID int64) error { @@ -289,12 +346,17 @@ func (s *Service) CancelSubscriptionForUser(ctx context.Context, subscriptionID, if err := s.subscriptionOwnedBy(ctx, subscriptionID, userID); err != nil { return err } - return s.store.CancelUserSubscription(ctx, subscriptionID) + if err := s.store.CancelUserSubscription(ctx, subscriptionID); err != nil { + return err + } + s.invalidateActiveSubscriptionCache(userID) + return nil } // AdminCancelSubscription cancels any learner subscription (admin panel). func (s *Service) AdminCancelSubscription(ctx context.Context, subscriptionID int64) (*domain.UserSubscription, error) { - if _, err := s.GetSubscriptionByID(ctx, subscriptionID); err != nil { + sub, err := s.GetSubscriptionByID(ctx, subscriptionID) + if err != nil { return nil, err } if err := s.store.CancelUserSubscription(ctx, subscriptionID); err != nil { @@ -305,6 +367,7 @@ func (s *Service) AdminCancelSubscription(ctx context.Context, subscriptionID in return nil, fmt.Errorf("cancel linked payments: %w", err) } } + s.invalidateActiveSubscriptionCache(sub.UserID) return s.GetSubscriptionByID(ctx, subscriptionID) } @@ -341,6 +404,7 @@ func (s *Service) AdminExtendSubscription(ctx context.Context, subscriptionID in if err := s.recordAdminPayment(ctx, updated, plan, "ADMIN_EXTEND", ¬e); err != nil { return nil, err } + s.invalidateActiveSubscriptionCache(updated.UserID) return updated, nil } diff --git a/internal/services/user/auth_status_cache.go b/internal/services/user/auth_status_cache.go new file mode 100644 index 00000000..b94ac6cf --- /dev/null +++ b/internal/services/user/auth_status_cache.go @@ -0,0 +1,73 @@ +package user + +import ( + "context" + "sync" + "time" + + "Yimaru-Backend/internal/domain" +) + +const authStatusTTL = 45 * time.Second + +type authStatusEntry struct { + status domain.UserStatus + expiresAt time.Time +} + +type authStatusCache struct { + mu sync.RWMutex + entries map[int64]authStatusEntry +} + +func (c *authStatusCache) get(userID int64) (domain.UserStatus, bool) { + c.mu.RLock() + entry, ok := c.entries[userID] + c.mu.RUnlock() + if !ok || time.Now().After(entry.expiresAt) { + return "", false + } + return entry.status, true +} + +func (c *authStatusCache) set(userID int64, status domain.UserStatus) { + c.mu.Lock() + if c.entries == nil { + c.entries = make(map[int64]authStatusEntry) + } + c.entries[userID] = authStatusEntry{ + status: status, + expiresAt: time.Now().Add(authStatusTTL), + } + c.mu.Unlock() +} + +func (c *authStatusCache) invalidate(userID int64) { + c.mu.Lock() + delete(c.entries, userID) + c.mu.Unlock() +} + +func (c *authStatusCache) invalidateAll() { + c.mu.Lock() + c.entries = make(map[int64]authStatusEntry) + c.mu.Unlock() +} + +// GetAuthStatus returns the account status used by auth middleware, with a short TTL cache +// so authenticated learner traffic does not hit the DB on every request. +func (s *Service) GetAuthStatus(ctx context.Context, userID int64) (domain.UserStatus, error) { + if status, ok := s.authStatusCache.get(userID); ok { + return status, nil + } + user, err := s.userStore.GetUserByID(ctx, userID) + if err != nil { + return "", err + } + s.authStatusCache.set(userID, user.Status) + return user.Status, nil +} + +func (s *Service) InvalidateAuthStatus(userID int64) { + s.authStatusCache.invalidate(userID) +} diff --git a/internal/services/user/direct.go b/internal/services/user/direct.go index 59ab6156..4cec38fc 100644 --- a/internal/services/user/direct.go +++ b/internal/services/user/direct.go @@ -141,15 +141,29 @@ func (s *Service) ListAccountDeletionRequests(ctx context.Context, filter domain } func (s *Service) UpdateUserStatus(ctx context.Context, req domain.UpdateUserStatusReq) error { - return s.userStore.UpdateUserStatus(ctx, req) + if err := s.userStore.UpdateUserStatus(ctx, req); err != nil { + return err + } + s.authStatusCache.invalidate(req.UserID) + return nil } func (s *Service) BulkDeactivateUsersByRole(ctx context.Context, role string, excludeUserID int64) (int64, error) { - return s.userStore.BulkDeactivateUsersByRole(ctx, role, excludeUserID) + n, err := s.userStore.BulkDeactivateUsersByRole(ctx, role, excludeUserID) + if err != nil { + return 0, err + } + s.authStatusCache.invalidateAll() + return n, nil } func (s *Service) BulkReactivateUsersByRole(ctx context.Context, role string, excludeUserID int64) (int64, error) { - return s.userStore.BulkReactivateUsersByRole(ctx, role, excludeUserID) + n, err := s.userStore.BulkReactivateUsersByRole(ctx, role, excludeUserID) + if err != nil { + return 0, err + } + s.authStatusCache.invalidateAll() + return n, nil } func (s *Service) GetUserById(ctx context.Context, id int64) (domain.User, error) { diff --git a/internal/services/user/service.go b/internal/services/user/service.go index 69ea66b8..7e84bebc 100644 --- a/internal/services/user/service.go +++ b/internal/services/user/service.go @@ -21,6 +21,7 @@ type Service struct { emailTemplateSvc *emailtemplates.Service profileFieldOptionSvc *profilefieldoptions.Service config *config.Config + authStatusCache authStatusCache } func NewService( diff --git a/internal/web_server/handlers/admin_user_detail_handler.go b/internal/web_server/handlers/admin_user_detail_handler.go index ea11a11a..f9ea479e 100644 --- a/internal/web_server/handlers/admin_user_detail_handler.go +++ b/internal/web_server/handlers/admin_user_detail_handler.go @@ -6,6 +6,7 @@ import ( "strconv" "Yimaru-Backend/internal/domain" + lmsprogress "Yimaru-Backend/internal/services/lmsprogress" "github.com/gofiber/fiber/v2" ) @@ -128,7 +129,8 @@ func (h *Handler) AdminGetUserLearningActivityDetails(c *fiber.Ctx) error { }) } - lmsProgress, err := h.buildLMSProgressSummary(c.Context(), domain.RoleStudent, targetID, true) + ctx := lmsprogress.WithRequestMemo(c.Context()) + lmsProgress, err := h.buildLMSProgressSummary(ctx, domain.RoleStudent, targetID, true) if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to load LMS progress summary", @@ -144,7 +146,7 @@ func (h *Handler) AdminGetUserLearningActivityDetails(c *fiber.Ctx) error { }) } - examPrepProgress, err := h.buildExamPrepProgressSummary(c.Context(), domain.RoleStudent, targetID, true) + examPrepProgress, err := h.buildExamPrepProgressSummary(ctx, domain.RoleStudent, targetID, true) if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to load exam prep progress summary", @@ -230,6 +232,7 @@ func mapAdminUserSubscriptionPayments(payments []domain.Payment) []domain.AdminU } func (h *Handler) buildExamPrepProgressSummary(ctx context.Context, role domain.Role, userID int64, publishedOnly bool) (domain.ExamPrepProgressSummary, error) { + ctx = lmsprogress.WithRequestMemo(ctx) catalogCourses, err := h.listAllExamPrepCatalogCourses(ctx, publishedOnly) if err != nil { return domain.ExamPrepProgressSummary{}, err diff --git a/internal/web_server/handlers/course_handler.go b/internal/web_server/handlers/course_handler.go index c8cec157..8781cbab 100644 --- a/internal/web_server/handlers/course_handler.go +++ b/internal/web_server/handlers/course_handler.go @@ -4,6 +4,7 @@ import ( "Yimaru-Backend/internal/domain" "Yimaru-Backend/internal/services/courses" "Yimaru-Backend/internal/services/programs" + lmsprogress "Yimaru-Backend/internal/services/lmsprogress" "context" "errors" "strconv" @@ -154,8 +155,9 @@ func (h *Handler) ListCoursesByProgram(c *fiber.Ctx) error { annotateCoursesEffectiveAccessTier(role, items, program) } uid := c.Locals("user_id").(int64) + ctx := lmsprogress.WithRequestMemo(c.Context()) for i := range items { - if err := h.lmsProgressSvc.ApplyAccessCourse(c.Context(), role, uid, &items[i]); err != nil { + if err := h.lmsProgressSvc.ApplyAccessCourse(ctx, role, uid, &items[i]); err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to build course list", Error: err.Error(), diff --git a/internal/web_server/handlers/lesson_handler.go b/internal/web_server/handlers/lesson_handler.go index 20203275..a40c5c1e 100644 --- a/internal/web_server/handlers/lesson_handler.go +++ b/internal/web_server/handlers/lesson_handler.go @@ -4,6 +4,7 @@ import ( "Yimaru-Backend/internal/domain" "Yimaru-Backend/internal/services/lessons" "Yimaru-Backend/internal/services/modules" + lmsprogress "Yimaru-Backend/internal/services/lmsprogress" "context" "errors" "fmt" @@ -106,8 +107,9 @@ func (h *Handler) ListLessonsByModule(c *fiber.Ctx) error { } uid := c.Locals("user_id").(int64) role := c.Locals("role").(domain.Role) + ctx := lmsprogress.WithRequestMemo(c.Context()) for i := range items { - if err := h.lmsProgressSvc.ApplyAccessLesson(c.Context(), role, uid, &items[i]); err != nil { + if err := h.lmsProgressSvc.ApplyAccessLesson(ctx, role, uid, &items[i]); err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to build lesson list", Error: err.Error(), diff --git a/internal/web_server/handlers/lms_progress_handler.go b/internal/web_server/handlers/lms_progress_handler.go index d2d2486f..a8d24eb7 100644 --- a/internal/web_server/handlers/lms_progress_handler.go +++ b/internal/web_server/handlers/lms_progress_handler.go @@ -6,6 +6,7 @@ import ( "strconv" "Yimaru-Backend/internal/domain" + lmsprogress "Yimaru-Backend/internal/services/lmsprogress" "github.com/gofiber/fiber/v2" ) @@ -48,14 +49,15 @@ func (h *Handler) GetMyLMSProgress(c *fiber.Ctx) error { func (h *Handler) GetMyLMSProgressSummary(c *fiber.Ctx) error { uid := c.Locals("user_id").(int64) role := c.Locals("role").(domain.Role) - summary, err := h.buildLMSProgressSummary(c.Context(), role, uid, !h.canManageLessons(c)) + ctx := lmsprogress.WithRequestMemo(c.Context()) + summary, err := h.buildLMSProgressSummary(ctx, role, uid, !h.canManageLessons(c)) if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to load learning progress summary", Error: err.Error(), }) } - examPrep, err := h.buildExamPrepProgressSummary(c.Context(), role, uid, !h.canManageExamPrepCatalogCourses(c)) + examPrep, err := h.buildExamPrepProgressSummary(ctx, role, uid, !h.canManageExamPrepCatalogCourses(c)) if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to load exam prep progress summary", @@ -179,6 +181,7 @@ func (h *Handler) AdminGetUserRecentActivity(c *fiber.Ctx) error { } func (h *Handler) buildLMSProgressSummary(ctx context.Context, role domain.Role, userID int64, publishedOnly bool) (domain.LMSProgressSummary, error) { + ctx = lmsprogress.WithRequestMemo(ctx) programs, err := h.listAllPrograms(ctx, publishedOnly) if err != nil { return domain.LMSProgressSummary{}, err diff --git a/internal/web_server/handlers/module_handler.go b/internal/web_server/handlers/module_handler.go index 131d2562..283744fd 100644 --- a/internal/web_server/handlers/module_handler.go +++ b/internal/web_server/handlers/module_handler.go @@ -4,6 +4,7 @@ import ( "Yimaru-Backend/internal/domain" "Yimaru-Backend/internal/services/courses" "Yimaru-Backend/internal/services/modules" + lmsprogress "Yimaru-Backend/internal/services/lmsprogress" "context" "errors" "strconv" @@ -121,8 +122,9 @@ func (h *Handler) ListModulesByCourse(c *fiber.Ctx) error { } uid := c.Locals("user_id").(int64) role := c.Locals("role").(domain.Role) + ctx := lmsprogress.WithRequestMemo(c.Context()) for i := range items { - if err := h.lmsProgressSvc.ApplyAccessModule(c.Context(), role, uid, &items[i]); err != nil { + if err := h.lmsProgressSvc.ApplyAccessModule(ctx, role, uid, &items[i]); err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to build module list", Error: err.Error(), diff --git a/internal/web_server/handlers/program_handler.go b/internal/web_server/handlers/program_handler.go index 78796d29..02125565 100644 --- a/internal/web_server/handlers/program_handler.go +++ b/internal/web_server/handlers/program_handler.go @@ -3,6 +3,7 @@ package handlers import ( "Yimaru-Backend/internal/domain" "Yimaru-Backend/internal/services/programs" + lmsprogress "Yimaru-Backend/internal/services/lmsprogress" "context" "errors" "strconv" @@ -84,8 +85,9 @@ func (h *Handler) ListPrograms(c *fiber.Ctx) error { } annotateProgramsEffectiveAccessTier(role, items) uid := c.Locals("user_id").(int64) + ctx := lmsprogress.WithRequestMemo(c.Context()) for i := range items { - if err := h.lmsProgressSvc.ApplyAccessProgram(c.Context(), role, uid, &items[i]); err != nil { + if err := h.lmsProgressSvc.ApplyAccessProgram(ctx, role, uid, &items[i]); err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to build program list", Error: err.Error(), diff --git a/internal/web_server/handlers/questions.go b/internal/web_server/handlers/questions.go index 015b2970..70b07805 100644 --- a/internal/web_server/handlers/questions.go +++ b/internal/web_server/handlers/questions.go @@ -577,20 +577,26 @@ func (h *Handler) UpdateQuestion(c *fiber.Ctx) error { } var options []domain.CreateQuestionOptionInput - for _, opt := range req.Options { - options = append(options, domain.CreateQuestionOptionInput{ - OptionText: opt.OptionText, - OptionOrder: opt.OptionOrder, - IsCorrect: opt.IsCorrect, - }) + if req.Options != nil { + options = make([]domain.CreateQuestionOptionInput, 0, len(req.Options)) + for _, opt := range req.Options { + options = append(options, domain.CreateQuestionOptionInput{ + OptionText: opt.OptionText, + OptionOrder: opt.OptionOrder, + IsCorrect: opt.IsCorrect, + }) + } } var shortAnswers []domain.CreateShortAnswerInput - for _, sa := range req.ShortAnswers { - shortAnswers = append(shortAnswers, domain.CreateShortAnswerInput{ - AcceptableAnswer: sa.AcceptableAnswer, - MatchType: sa.MatchType, - }) + if req.ShortAnswers != nil { + shortAnswers = make([]domain.CreateShortAnswerInput, 0, len(req.ShortAnswers)) + for _, sa := range req.ShortAnswers { + shortAnswers = append(shortAnswers, domain.CreateShortAnswerInput{ + AcceptableAnswer: sa.AcceptableAnswer, + MatchType: sa.MatchType, + }) + } } questionType := normalizeRuntimeQuestionType(existingQuestion.QuestionType) @@ -1593,12 +1599,23 @@ func (h *Handler) GetQuestionsInSet(c *fiber.Ctx) error { questionResponses := make([]questionRes, 0, len(items)) memberships := domain.MembershipsFromQuestionSetItems(items) + ids := make([]int64, 0, len(items)) for _, item := range items { - question, err := h.questionsSvc.GetQuestionWithDetails(c.Context(), item.QuestionID) - if err != nil { + ids = append(ids, item.QuestionID) + } + questionsByID, err := h.questionsSvc.GetQuestionsWithDetailsByIDs(c.Context(), ids) + if err != nil { + return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ + Message: "Failed to get question details", + Error: err.Error(), + }) + } + for _, item := range items { + question, ok := questionsByID[item.QuestionID] + if !ok { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to get question details", - Error: err.Error(), + Error: "question not found", }) } diff --git a/internal/web_server/middleware.go b/internal/web_server/middleware.go index 53db3e54..f3626576 100644 --- a/internal/web_server/middleware.go +++ b/internal/web_server/middleware.go @@ -28,16 +28,6 @@ func (a *App) authMiddleware(c *fiber.Ctx) error { // Try lowercase as fallback authHeader = strings.TrimSpace(c.Get("authorization")) } - fmt.Println("--------------------------------") - fmt.Println("All Headers:") - allHeaders := c.GetReqHeaders() - for key, value := range allHeaders { - fmt.Printf(" %s: %s\n", key, value) - } - fmt.Println("userAgent", userAgent) - fmt.Println("ip", ip) - fmt.Println("authHeader", authHeader) - fmt.Println("--------------------------------") if authHeader == "" { a.mongoLoggerSvc.Info("Authorization header missing", zap.Int("status_code", fiber.StatusUnauthorized), @@ -109,7 +99,7 @@ func (a *App) authMiddleware(c *fiber.Ctx) error { userRole := claim.Role if userRole.IsCustomerLearnerRole() { - user, err := a.userSvc.GetUserByID(c.Context(), claim.UserId) + status, err := a.userSvc.GetAuthStatus(c.Context(), claim.UserId) if err != nil { if errors.Is(err, domain.ErrUserNotFound) { return fiber.NewError(fiber.StatusUnauthorized, "Invalid access token") @@ -122,7 +112,8 @@ func (a *App) authMiddleware(c *fiber.Ctx) error { ) return fiber.NewError(fiber.StatusInternalServerError, "Failed to validate user account") } - if err := domain.ValidateUserCanAuthenticate(user.Status); err != nil { + if err := domain.ValidateUserCanAuthenticate(status); err != nil { + a.userSvc.InvalidateAuthStatus(claim.UserId) switch { case errors.Is(err, domain.ErrUserAccountLocked): return fiber.NewError(fiber.StatusForbidden, "Account is locked") @@ -661,8 +652,6 @@ func (a *App) TenantAuthMiddleware(c *fiber.Ctx) error { return fiber.NewError(fiber.StatusInternalServerError, "invalid company_id") } - fmt.Printf("\nTenant successfully authenticated!\n") - return c.Next() }