Files
breakpilot-lehrer/school-service/internal/services/timetable_solutions.go
T
Benjamin Admin f042f2896b Phase 5: Timefold timetable-solver-service + solution persistence
school-service additions:
  - tt_solution + tt_lesson migration. tt_lesson carries three UNIQUEs
    (solution+class, solution+teacher, solution+room per slot) so the
    DB itself rejects any double-booking the solver might emit by
    mistake.
  - Solution CRUD + GET solutions/:id/lessons endpoint with joined
    class/subject/teacher/room names for display.
  - POST /timetable/solutions creates the row then fires off the
    solver-service via HTTP (5s timeout, mark failed if unreachable).
  - SOLVER_SERVICE_URL config wired through main.go/handlers.

New service timetable-solver-service:
  - Python 3.11 + FastAPI + Timefold Solver 1.21 (Apache-2.0). Dockerfile
    bundles OpenJDK 17 since Timefold for Python is a JPype bridge.
  - app/domain.py — Timefold @planning_entity Lesson with timeslot+room
    as PlanningVariables; @planning_solution Timetable holds problem
    facts (rooms/teachers/etc.) AND rule-fact collections.
  - app/rules.py — frozen dataclasses mirroring 6 of the 15 tt_
    constraint_* tables initially.
  - app/constraints.py — ConstraintProvider with 3 universal hard
    constraints (no double-booking) + 5 DB-driven constraints
    (teacher_unavailable_day/window, teacher_excluded_room,
    room_unavailable, room_requires_type) + 1 quality soft constraint
    (subject_preferred_period). Remaining 9 constraint types ready to
    plug in via the same join pattern.
  - app/repository.py — async loaders for stammdaten + rules; builds
    one Lesson per (curriculum row × weekly_hours), skipping rows
    without a tt_assignment teacher.
  - app/runner.py — runs solver in ThreadPoolExecutor so the FastAPI
    event loop stays responsive. Updates tt_solution status
    pending→running→completed|infeasible|failed.
  - app/main.py — POST /api/v1/solve (202 Accepted, background task),
    GET /api/v1/jobs/{id}, /health. School-service polls tt_solution
    directly instead of GET /jobs for the typical case.
  - docker-compose.yml adds the service on port 8095, depending on
    core-health-check.

Tests:
  - school-service: validator test for CreateTimetableSolutionRequest
    (allows empty name).
  - solver-service: tests/test_domain.py + tests/test_rules.py cover
    construction + hashability of the planning facts. Full solve flow
    deferred to Phase 8 integration with seed data.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 00:16:52 +02:00

150 lines
5.3 KiB
Go

package services
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/breakpilot/school-service/internal/models"
)
// TimetableSolutionService persists solver runs and forwards solve requests
// to the timetable-solver-service. The solver writes lesson rows back to the
// same DB once it finishes, so listing solutions = simple SELECTs here.
func (s *TimetableService) CreateSolution(ctx context.Context, userID string, req *models.CreateTimetableSolutionRequest) (*models.TimetableSolution, error) {
var sol models.TimetableSolution
err := s.db.QueryRow(ctx, `
INSERT INTO tt_solution (created_by_user_id, name, status)
VALUES ($1, $2, 'pending')
RETURNING id, created_by_user_id, COALESCE(name, ''), status, hard_score, soft_score,
COALESCE(error_message, ''), started_at, finished_at, created_at
`, userID, req.Name).Scan(
&sol.ID, &sol.CreatedByUserID, &sol.Name, &sol.Status,
&sol.HardScore, &sol.SoftScore, &sol.ErrorMessage,
&sol.StartedAt, &sol.FinishedAt, &sol.CreatedAt,
)
return &sol, err
}
func (s *TimetableService) ListSolutions(ctx context.Context, userID string) ([]models.TimetableSolution, error) {
rows, err := s.db.Query(ctx, `
SELECT id, created_by_user_id, COALESCE(name, ''), status, hard_score, soft_score,
COALESCE(error_message, ''), started_at, finished_at, created_at
FROM tt_solution WHERE created_by_user_id = $1 ORDER BY created_at DESC
`, userID)
if err != nil {
return nil, err
}
defer rows.Close()
var out []models.TimetableSolution
for rows.Next() {
var sol models.TimetableSolution
if err := rows.Scan(&sol.ID, &sol.CreatedByUserID, &sol.Name, &sol.Status,
&sol.HardScore, &sol.SoftScore, &sol.ErrorMessage,
&sol.StartedAt, &sol.FinishedAt, &sol.CreatedAt); err != nil {
return nil, err
}
out = append(out, sol)
}
return out, nil
}
func (s *TimetableService) GetSolution(ctx context.Context, id, userID string) (*models.TimetableSolution, error) {
var sol models.TimetableSolution
err := s.db.QueryRow(ctx, `
SELECT id, created_by_user_id, COALESCE(name, ''), status, hard_score, soft_score,
COALESCE(error_message, ''), started_at, finished_at, created_at
FROM tt_solution WHERE id = $1 AND created_by_user_id = $2
`, id, userID).Scan(
&sol.ID, &sol.CreatedByUserID, &sol.Name, &sol.Status,
&sol.HardScore, &sol.SoftScore, &sol.ErrorMessage,
&sol.StartedAt, &sol.FinishedAt, &sol.CreatedAt,
)
if err != nil {
return nil, err
}
return &sol, nil
}
func (s *TimetableService) ListLessons(ctx context.Context, solutionID, userID string) ([]models.TimetableLesson, error) {
rows, err := s.db.Query(ctx, `
SELECT l.id, l.solution_id, l.class_id, l.subject_id, l.teacher_id, l.room_id,
l.day_of_week, l.period_index, l.pinned, l.created_at,
cl.name, sub.name, t.last_name || ', ' || t.first_name,
COALESCE(r.name, '')
FROM tt_lesson l
JOIN tt_solution s ON l.solution_id = s.id
JOIN tt_class cl ON l.class_id = cl.id
JOIN tt_subject sub ON l.subject_id = sub.id
JOIN tt_teacher t ON l.teacher_id = t.id
LEFT JOIN tt_room r ON l.room_id = r.id
WHERE s.id = $1 AND s.created_by_user_id = $2
ORDER BY l.day_of_week, l.period_index
`, solutionID, userID)
if err != nil {
return nil, err
}
defer rows.Close()
var out []models.TimetableLesson
for rows.Next() {
var l models.TimetableLesson
if err := rows.Scan(&l.ID, &l.SolutionID, &l.ClassID, &l.SubjectID, &l.TeacherID, &l.RoomID,
&l.DayOfWeek, &l.PeriodIndex, &l.Pinned, &l.CreatedAt,
&l.ClassName, &l.SubjectName, &l.TeacherName, &l.RoomName); err != nil {
return nil, err
}
out = append(out, l)
}
return out, nil
}
func (s *TimetableService) DeleteSolution(ctx context.Context, id, userID string) error {
_, err := s.db.Exec(ctx, `DELETE FROM tt_solution WHERE id = $1 AND created_by_user_id = $2`, id, userID)
return err
}
// TriggerSolve hands the freshly-created solution off to the solver-service.
// The solver writes back to tt_solution/tt_lesson directly once finished, so
// from this side we just need to fire-and-forget and let the client poll.
func (s *TimetableService) TriggerSolve(ctx context.Context, solverURL, solutionID, userID string) error {
payload := map[string]string{
"solution_id": solutionID,
"created_by_user_id": userID,
}
body, _ := json.Marshal(payload)
// 5s timeout — solver should accept the job in milliseconds and run async.
reqCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(reqCtx, "POST", solverURL+"/api/v1/solve", bytes.NewReader(body))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
// Mark solution as failed so the user sees something went wrong.
_, _ = s.db.Exec(ctx, `
UPDATE tt_solution SET status = 'failed', error_message = $1, finished_at = NOW()
WHERE id = $2
`, "solver-service unreachable: "+err.Error(), solutionID)
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
_, _ = s.db.Exec(ctx, `
UPDATE tt_solution SET status = 'failed', error_message = $1, finished_at = NOW()
WHERE id = $2
`, fmt.Sprintf("solver returned HTTP %d", resp.StatusCode), solutionID)
return fmt.Errorf("solver returned HTTP %d", resp.StatusCode)
}
return nil
}