How nikotpab/class-scheduling-engine works
1. Overall shape
This is a backend microservice for academic timetable generation. The codebase is organized as a clean, layered architecture: API at the edge, application use cases in the middle, a domain model that holds the scheduling rules, and infrastructure adapters for database, solver, queueing, and WebSockets.
2. Request entrypoints
FastAPI is the HTTP entry layer in src/api. The main routes are:
- schedules for job submission, polling, listing, and deletion
- config for penalty-weight configuration
- ws for push notifications tied to a schedule job
The API returns a job_id immediately for generation requests, which implies schedule generation is asynchronous rather than blocking the HTTP request.
3. Application layer as orchestration
src/application/use_cases contains the two primary workflows:
- GenerateSchedule
- GetSchedule
These use cases mediate between request schemas and domain/infrastructure services. They are the main orchestration boundary where input is validated, the solver is invoked, and the resulting schedule/job state is persisted or retrieved.
4. Domain model and business rules
src/domain/entities defines the core scheduling objects: Teacher, Subject, Room, Timeslot, and Schedule.
src/domain/services/scheduling_service.py appears to encapsulate the scheduling business rules, while src/domain/value_objects/penalty_weights.py captures the tunable objective weights. This is where the hard constraints and soft penalties belong conceptually, independent of FastAPI or the database.
5. Ports define the dependency boundaries
The domain exposes abstract interfaces in src/domain/ports:
- i_solver
- i_schedule_repository
- i_event_publisher
These ports make the system extensible: the domain/application layers depend on abstractions, while infrastructure provides the concrete PuLP solver, database repository, and event delivery mechanism.
6. Solver subsystem
src/infrastructure/solvers contains the optimization backend. The README indicates the main solver is PuLP/CBC for exact mixed-integer linear programming, with a TabuSearchSolverStub as an extensibility point. A solver_factory selects the solver implementation based on the request/config.
This subsystem is the computational core of the service and is responsible for enforcing hard constraints and minimizing penalty terms.
7. Persistence subsystem
src/infrastructure/persistence uses async SQLAlchemy for runtime access and Alembic for schema evolution. models.py maps the storage schema, database.py manages DB connectivity, and schedule_repository.py implements the repository port.
The database is PostgreSQL 16, and the repository is the boundary between domain scheduling jobs/results and durable storage.
8. Async execution and messaging
src/infrastructure/messaging contains Celery integration, backed by Redis. Generation jobs are offloaded to a worker via Celery tasks, which fits the API’s immediate job_id response pattern. The queue layer decouples HTTP latency from potentially long-running MILP solving.
9. Real-time notifications
src/infrastructure/websockets/connection_manager.py supports WebSocket connections keyed by job_id. When a Celery task completes, the system can push job-completion notifications to connected clients instead of relying only on polling. This is the real-time complement to the /schedules/{job_id} status endpoint.
10. Configuration and runtime wiring
src/infrastructure/config/settings.py centralizes environment-based configuration using pydantic-settings. The API layer uses src/api/dependencies.py to wire repositories, solver selection, and services together.
Docker Compose and the Dockerfile package the full stack: API, worker, PostgreSQL, Redis, and Flower for monitoring.
11. Constraint model reflected in the README
The solver is built around academic timetabling constraints such as teacher availability, room capacity, no double-booking, and campus-transfer restrictions. The README also highlights teacher categories like REGULAR, PROCOM, PROJEX, and PROHES, which materially affect the solver objective and feasible assignments.
12. Testing and deployment boundaries
Unit tests cover the domain and solver logic, while integration tests exercise the API stack. Alembic migrations track schema changes. This separation matches the architecture: pure business logic can be tested without infrastructure, while full-stack behavior is verified against the composed services.
Main entry points: generate_schedule.py Generate · scheduling_service.py Scheduling service · main.py FastAPI app · i_schedule_repository.py Repo port
Components 25
API layer
HTTP entrypoints and dependency wiring.
- FastAPI app · Composes the HTTP service and registers routers.
src/api/main.py - Dependencies · Builds application services and infrastructure adapters for the API.
src/api/dependencies.py - Schedules API · Submit, poll, list, and delete schedule jobs.
src/api/routers/schedules.py - Config API · Exposes penalty-weight configuration.
src/api/routers/config.py - WebSocket API · Pushes schedule-job updates to connected clients.
src/api/routers/ws.py
Application layer
Use cases and transport schemas.
- Generate · Orchestrates schedule creation and persistence.
src/application/use_cases/generate_schedule.py - Get schedule · Retrieves existing schedule/job state.
src/application/use_cases/get_schedule.py - Input schemas · Request models for schedule generation and related actions.
src/application/schemas/inputs.py - Output schemas · Response models returned by the API.
src/application/schemas/outputs.py
Domain model
Core scheduling concepts and business rules.
- Scheduling service · Encapsulates scheduling rules and constraint logic.
src/domain/services/scheduling_service.py - Penalty weights · Tunables for soft constraints and optimization objective.
src/domain/value_objects/penalty_weights.py - Entities · Teachers, subjects, rooms, timeslots, and schedules.
src/domain/entities/schedule.py - Solver port · Abstract optimization interface.
src/domain/ports/i_solver.py - Repo port · Abstract schedule persistence interface.
src/domain/ports/i_schedule_repository.py - Event port · Abstract notification publishing interface.
src/domain/ports/i_event_publisher.py
Infrastructure
Concrete adapters for persistence, solver, messaging, and websockets.
- Settings · Environment-based runtime configuration.
src/infrastructure/config/settings.py - Solver factory · Selects the solver implementation for a request or config.
src/infrastructure/solvers/solver_factory.py - PuLP solver · MILP solver implementation for timetable generation.
src/infrastructure/solvers/pulp_solver.py - Schedule repo · SQLAlchemy-backed implementation of the schedule repository port.
src/infrastructure/persistence/schedule_repository.py - Database · Database session and connectivity layer.
src/infrastructure/persistence/database.py - Celery tasks · Background job execution for schedule generation.
src/infrastructure/messaging/tasks.py - Celery app · Queue wiring for asynchronous execution.
src/infrastructure/messaging/celery_app.py - Conn manager · Tracks WebSocket connections keyed by job ID.
src/infrastructure/websockets/connection_manager.py
Tests
Unit and integration coverage.
- Unit tests · Covers domain entities and solver behavior.
tests/unit/test_domain_entities.py - Integration tests · Exercises the API stack end to end.
tests/integration/test_api.py
Connections 29
- FastAPI app → Schedules API: registers · Main app mounts the schedules routes.
- FastAPI app → Config API: registers · Main app mounts configuration routes.
- FastAPI app → WebSocket API: registers · Main app mounts websocket routes.
- Schedules API → Generate: calls · Submission endpoints start schedule generation.
- Schedules API → Get schedule: calls · Poll/list/delete endpoints retrieve schedule state.
- Config API → Penalty weights: uses · Configuration endpoints expose penalty tuning.
- WebSocket API → Conn manager: uses · WebSocket routes coordinate connections through the manager.
- Dependencies → Solver port: binds · Wires a concrete solver behind the solver port.
- Dependencies → Repo port: binds · Wires persistence behind the repository port.
- Dependencies → Event port: binds · Wires event delivery behind the publisher port.
- Generate → Input schemas: validates · Use case accepts request DTOs.
- Generate → Scheduling service: orchestrates · Coordinates business rules around scheduling.
- Generate → Solver port: invokes · Delegates optimization to the solver abstraction.
- Generate → Repo port: persists · Stores generated schedule/job state.
- Generate → Event port: publishes · Emits job progress or completion events.
- Get schedule → Repo port: reads · Fetches schedule/job state from persistence.
- Scheduling service → Entities: operates on · Business rules are expressed over core scheduling entities.
- Scheduling service → Penalty weights: applies · Uses penalty weights to score schedules.
- Scheduling service → Solver port: depends on · Service remains independent of solver implementation.
- Solver factory → PuLP solver: creates · Factory selects the concrete optimization backend.
- PuLP solver → Entities: solves for · Solver produces schedules over domain objects.
- Schedule repo → Database: uses · Repository relies on DB connectivity and sessions.
- Schedule repo → Repo port: implements · Concrete adapter for the repository port.
- Celery tasks → Generate: runs · Background worker executes generation workflows.
- Celery tasks → Celery app: queues via · Celery is configured for asynchronous task execution.
- Conn manager → Event port: implements · WebSocket delivery can satisfy event publication.
- Unit tests → Entities: covers · Unit tests validate core domain objects.
- Unit tests → PuLP solver: covers · Unit tests validate solver behavior.
- Integration tests → FastAPI app: covers · Integration tests exercise the composed API stack.