# me-umar/fastapi-crons architecture

> Architecture diagram of the GitHub repository me-umar/fastapi-crons, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-05-13). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/me-umar/fastapi-crons
- Repository: https://github.com/me-umar/fastapi-crons

## Overview

##### Project type and purpose
- This is an open-source Python library that extends FastAPI with cron-style scheduled job support. It provides decorator-based job definitions, a background scheduler, CLI management, a monitoring HTTP endpoint, and a pluggable SQLite (or Redis) state backend.

##### File structure
- Top-level package “fastapi_crons/”: core modules
- cli.py       – CLI entry points (“fastapi_cron list”, “run_job”)
- endpoints.py – `/crons` monitoring router
- hooks.py     – plugin and lifecycle hooks
- job.py       – job metadata and decorator logic
- runner.py    – dispatches jobs (async vs thread)
- scheduler.py – central scheduler loop (parses cron, triggers jobs)
- state.py     – default SQLite backend (aiosqlite) + interface for custom backends
- __init__.py  – Crons class integration and FastAPI startup/shutdown hooks
- Project configuration: pyproject.toml, MANIFEST.in, README.md, LICENSE

##### README for architecture clues
- “Architecture Overview” section already sketches:
- FastAPI App
- Crons() extension
- SQLite Backend
- `/crons` endpoint
- CLI tool
- Mentions optional Redis locking, retry policies, manual triggers

##### Main components
a. FastAPI Application
- Registers Crons extension
- Includes `/crons` router
- Hosts user-defined endpoints alongside cron monitoring
b. Crons Extension
- At startup: scans and registers decorated jobs
- Spins up Scheduler loop
- Hooks into FastAPI startup/shutdown events
c. Scheduler
- Reads cron expressions from job registry
- Every minute (or tick) determines jobs to run
- Delegates execution to Runner
d. Runner
- If job is async: executes directly on the event loop
- If job is sync: runs via `asyncio.to_thread()`
- On completion: updates state backend
- On error: invokes isolated error handler
e. State Backend
- Default: SQLite database (`cron_state.db`) via aiosqlite
- Tracks `last_run` timestamps in `job_state` table
- Pluggable interface for Redis (distributed locks), custom backends
f. HTTP Monitoring Endpoint
- GET `/crons` returns job list with `name`, `expr`, `tags`, `last_run`, `next_run`
g. CLI Tool
- Exposed via console script `fastapi_cron`
- Commands: `list`, `run_job <name>`
- Uses the same job registry and runner code

##### Relationships and data flows
- FastAPI startup → instantiate Crons → register jobs → start Scheduler
- Scheduler tick → query Job Registry → send jobs to Runner
- Runner → execute job → update State Backend → scheduler computes next_run
- Client requests `/crons` → FastAPI → endpoints.py reads registry + state → returns JSON
- Developer runs CLI → cli.py loads registry → dispatches run to Runner

##### Important architectural patterns/design principles
- Inversion of Control: Crons hooks into FastAPI lifecycle
- Dependency Injection: state backend is pluggable (strategy pattern)
- Async/Synchronous execution transparently unified (adapter pattern)
- Single responsibility: separate modules for CLI, HTTP, scheduling, state

##### Essential details
- Don’t just show FastAPI; break out Crons sub-modules and their interactions
- How state flows from job execution back into persistence
- Both HTTP-based monitoring and CLI-based triggers
- Pluggability points (state_backend, error hooks, retry plugin)

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% User Layer
    subgraph "User Layer"
        API["FastAPI Application"]:::user
        UserJobs["User-defined Jobs"]:::user
        Client["API Client"]:::external
    end

    %% Crons Extension Layer
    subgraph "Crons Extension"
        Init["Crons Extension Setup"]:::lib
        Hooks["Hooks & Lifecycle"]:::lib
        JobReg["Job Registry"]:::lib
        Scheduler["Scheduler Loop"]:::lib
        Runner["Runner (async/sync)"]:::lib
        State["State Backend Interface\n(Default SQLite/Redis)"]:::lib
        Endpoint["HTTP `/crons` Endpoint"]:::lib
        CLI["CLI Tool"]:::lib
    end

    %% External Persistence
    subgraph "External Persistence"
        SQLite["SQLite (`cron_state.db`)"]:::external
        Redis["Redis (optional)"]:::external
    end

    %% Relationships
    API -->|"include Crons\nstartup hooks"| Init
    Init -->|hooks into| Hooks
    Init -->|register jobs| JobReg
    UserJobs -->|decorated jobs| JobReg

    JobReg -->|provides cron expressions| Scheduler
    Scheduler -->|"tick every minute"| Scheduler
    Scheduler -->|"execute job"| Runner
    Runner -->|"update state"| State

    State -->|persist last_run| SQLite
    State -.->|optional distributed lock| Redis

    Client -->|"HTTP GET /crons"| Endpoint
    Endpoint -->|query registry & state| JobReg
    Endpoint -->|query registry & state| State
    Endpoint -->|"return JSON status"| Client

    CLI -->|list & run_job| JobReg
    CLI -->|"dispatch run"| Runner

    %% Click Events
    click Init "https://github.com/me-umar/fastapi-crons/blob/main/fastapi_crons/__init__.py"
    click Hooks "https://github.com/me-umar/fastapi-crons/blob/main/fastapi_crons/hooks.py"
    click JobReg "https://github.com/me-umar/fastapi-crons/blob/main/fastapi_crons/job.py"
    click Scheduler "https://github.com/me-umar/fastapi-crons/blob/main/fastapi_crons/scheduler.py"
    click Runner "https://github.com/me-umar/fastapi-crons/blob/main/fastapi_crons/runner.py"
    click State "https://github.com/me-umar/fastapi-crons/blob/main/fastapi_crons/state.py"
    click Endpoint "https://github.com/me-umar/fastapi-crons/blob/main/fastapi_crons/endpoints.py"
    click CLI "https://github.com/me-umar/fastapi-crons/blob/main/fastapi_crons/cli.py"

    %% Styles
    classDef user fill:#f9f,stroke:#333,stroke-width:1px
    classDef lib fill:#bbf,stroke:#333,stroke-width:1px
    classDef external fill:#bfb,stroke:#333,stroke-width:1px
```
