fastpluggy-cli 0.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fastpluggy_cli/__init__.py +0 -0
- fastpluggy_cli/cli.py +1000 -0
- fastpluggy_cli/scaffold_templates/main.py.j2 +21 -0
- fastpluggy_cli/scaffold_templates/plugin/config.py.j2 +22 -0
- fastpluggy_cli/scaffold_templates/plugin/index.html.j2 +10 -0
- fastpluggy_cli/scaffold_templates/plugin/models/__init__.py.j2 +1 -0
- fastpluggy_cli/scaffold_templates/plugin/models/context.py.j2 +37 -0
- fastpluggy_cli/scaffold_templates/plugin/models/report.py.j2 +27 -0
- fastpluggy_cli/scaffold_templates/plugin/models/scheduled.py.j2 +38 -0
- fastpluggy_cli/scaffold_templates/plugin/plugin.py.j2 +49 -0
- fastpluggy_cli/scaffold_templates/plugin/pyproject.toml.j2 +34 -0
- fastpluggy_cli/scaffold_templates/plugin/router.py.j2 +37 -0
- fastpluggy_cli/scaffold_templates/plugin/runner.py.j2 +171 -0
- fastpluggy_cli/scaffold_templates/plugin/tasks/__init__.py.j2 +1 -0
- fastpluggy_cli/scaffold_templates/plugin/tasks/maintenance.py.j2 +50 -0
- fastpluggy_cli/scaffold_templates/plugin/tasks/plugin_update.py.j2 +53 -0
- fastpluggy_cli/scaffold_templates/plugin/tasks/scheduler.py.j2 +73 -0
- fastpluggy_cli-0.1.1.dist-info/METADATA +20 -0
- fastpluggy_cli-0.1.1.dist-info/RECORD +22 -0
- fastpluggy_cli-0.1.1.dist-info/WHEEL +5 -0
- fastpluggy_cli-0.1.1.dist-info/entry_points.txt +3 -0
- fastpluggy_cli-0.1.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
from fastapi import FastAPI
|
|
5
|
+
from fastpluggy.fastpluggy import FastPluggy
|
|
6
|
+
|
|
7
|
+
# Configure logging
|
|
8
|
+
logging.basicConfig(level=logging.INFO)
|
|
9
|
+
|
|
10
|
+
# Create FastAPI app
|
|
11
|
+
app = FastAPI()
|
|
12
|
+
|
|
13
|
+
# Initialize FastPluggy (discovers and loads plugins via entry points)
|
|
14
|
+
fast_pluggy = FastPluggy(app)
|
|
15
|
+
|
|
16
|
+
# Run the application using Uvicorn or another ASGI server
|
|
17
|
+
if __name__ == "__main__":
|
|
18
|
+
import uvicorn
|
|
19
|
+
|
|
20
|
+
port = int(os.getenv("PORT", "8000"))
|
|
21
|
+
uvicorn.run(app, host="127.0.0.1", port=port)
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# config.py
|
|
2
|
+
from pydantic import BaseModel, Field
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class {{ plugin_class }}Settings(BaseModel):
|
|
6
|
+
"""Settings for the {{ plugin_name }} plugin."""
|
|
7
|
+
|
|
8
|
+
# General settings
|
|
9
|
+
debug_mode: bool = Field(False, description="Enable debug mode")
|
|
10
|
+
|
|
11
|
+
# Feature flags
|
|
12
|
+
enable_feature_x: bool = Field(True, description="Enable feature X")
|
|
13
|
+
enable_feature_y: bool = Field(False, description="Enable feature Y")
|
|
14
|
+
|
|
15
|
+
# API settings
|
|
16
|
+
api_timeout: int = Field(30, description="API request timeout in seconds")
|
|
17
|
+
|
|
18
|
+
# UI settings
|
|
19
|
+
items_per_page: int = Field(20, description="Number of items to display per page")
|
|
20
|
+
|
|
21
|
+
# Custom settings
|
|
22
|
+
custom_setting: str = Field("default_value", description="A custom setting for your plugin")
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# models package
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# models/context.py
|
|
2
|
+
from datetime import datetime
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
from sqlalchemy import Column, String, DateTime, Integer, Boolean, Text, JSON
|
|
6
|
+
|
|
7
|
+
from fastpluggy.core.database import Base
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class TaskContextDB(Base):
|
|
11
|
+
"""Database model for task execution context."""
|
|
12
|
+
|
|
13
|
+
__tablename__ = "{{ plugin_name }}_task_contexts"
|
|
14
|
+
|
|
15
|
+
id = Column(Integer, primary_key=True, autoincrement=True)
|
|
16
|
+
task_id = Column(String(36), unique=True, index=True)
|
|
17
|
+
task_name = Column(String(255), nullable=False)
|
|
18
|
+
|
|
19
|
+
# Status
|
|
20
|
+
status = Column(String(50), nullable=False, default="pending")
|
|
21
|
+
error = Column(Text, nullable=True)
|
|
22
|
+
|
|
23
|
+
# Timing
|
|
24
|
+
created_at = Column(DateTime, default=datetime.now)
|
|
25
|
+
started_at = Column(DateTime, nullable=True)
|
|
26
|
+
completed_at = Column(DateTime, nullable=True)
|
|
27
|
+
|
|
28
|
+
# Task details
|
|
29
|
+
parameters = Column(JSON, nullable=True)
|
|
30
|
+
result = Column(JSON, nullable=True)
|
|
31
|
+
|
|
32
|
+
# Metadata
|
|
33
|
+
user_id = Column(String(255), nullable=True)
|
|
34
|
+
scheduled_task_id = Column(String(36), nullable=True)
|
|
35
|
+
|
|
36
|
+
def __repr__(self):
|
|
37
|
+
return f"<TaskContext {self.task_name} ({self.task_id})>"
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# models/report.py
|
|
2
|
+
from datetime import datetime
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
from sqlalchemy import Column, String, DateTime, Integer, Boolean, Text, JSON, ForeignKey
|
|
6
|
+
from sqlalchemy.orm import relationship
|
|
7
|
+
|
|
8
|
+
from fastpluggy.core.database import Base
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class TaskReportDB(Base):
|
|
12
|
+
"""Database model for task execution reports."""
|
|
13
|
+
|
|
14
|
+
__tablename__ = "{{ plugin_name }}_task_reports"
|
|
15
|
+
|
|
16
|
+
id = Column(Integer, primary_key=True, autoincrement=True)
|
|
17
|
+
task_id = Column(String(36), ForeignKey("{{ plugin_name }}_task_contexts.task_id"), index=True)
|
|
18
|
+
|
|
19
|
+
# Report content
|
|
20
|
+
report_type = Column(String(50), nullable=False)
|
|
21
|
+
content = Column(Text, nullable=True)
|
|
22
|
+
|
|
23
|
+
# Metadata
|
|
24
|
+
created_at = Column(DateTime, default=datetime.now)
|
|
25
|
+
|
|
26
|
+
def __repr__(self):
|
|
27
|
+
return f"<TaskReport {self.report_type} for {self.task_id}>"
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# models/scheduled.py
|
|
2
|
+
from datetime import datetime
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
from sqlalchemy import Column, String, DateTime, Integer, Boolean, Text, JSON
|
|
6
|
+
|
|
7
|
+
from fastpluggy.core.database import Base
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ScheduledTaskDB(Base):
|
|
11
|
+
"""Database model for scheduled tasks."""
|
|
12
|
+
|
|
13
|
+
__tablename__ = "{{ plugin_name }}_scheduled_tasks"
|
|
14
|
+
|
|
15
|
+
id = Column(Integer, primary_key=True, autoincrement=True)
|
|
16
|
+
task_id = Column(String(36), unique=True, index=True)
|
|
17
|
+
task_name = Column(String(255), nullable=False)
|
|
18
|
+
function_path = Column(String(255), nullable=False)
|
|
19
|
+
|
|
20
|
+
# Schedule type (cron or interval)
|
|
21
|
+
schedule_type = Column(String(50), nullable=False)
|
|
22
|
+
cron_expression = Column(String(100), nullable=True)
|
|
23
|
+
interval_seconds = Column(Integer, nullable=True)
|
|
24
|
+
|
|
25
|
+
# Task parameters
|
|
26
|
+
parameters = Column(JSON, nullable=True)
|
|
27
|
+
|
|
28
|
+
# Status
|
|
29
|
+
enabled = Column(Boolean, default=True)
|
|
30
|
+
last_run = Column(DateTime, nullable=True)
|
|
31
|
+
next_run = Column(DateTime, nullable=True)
|
|
32
|
+
|
|
33
|
+
# Metadata
|
|
34
|
+
created_at = Column(DateTime, default=datetime.now)
|
|
35
|
+
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
|
|
36
|
+
|
|
37
|
+
def __repr__(self):
|
|
38
|
+
return f"<ScheduledTask {self.task_name} ({self.task_id})>"
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# plugin.py
|
|
2
|
+
from typing import Annotated, Any, List
|
|
3
|
+
|
|
4
|
+
from fastpluggy.core.module_base import FastPluggyBaseModule
|
|
5
|
+
from fastpluggy.core.tools.inspect_tools import InjectDependency
|
|
6
|
+
{% if with_config %}
|
|
7
|
+
from .config import {{ plugin_class }}Settings
|
|
8
|
+
{% endif %}
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def get_router():
|
|
12
|
+
"""Get the router for this plugin."""
|
|
13
|
+
from .router import router
|
|
14
|
+
return router
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class {{ plugin_class }}(FastPluggyBaseModule):
|
|
18
|
+
"""
|
|
19
|
+
{{ plugin_label }} plugin for FastPluggy.
|
|
20
|
+
"""
|
|
21
|
+
# Basic plugin information
|
|
22
|
+
module_name: str = "{{ plugin_name }}"
|
|
23
|
+
module_version: str = "0.1.0"
|
|
24
|
+
|
|
25
|
+
# Menu configuration
|
|
26
|
+
module_menu_name: str = "{{ plugin_label }}"
|
|
27
|
+
module_menu_icon: str = "{{ icon }}"
|
|
28
|
+
module_menu_type: str = "{{ menu_type }}"
|
|
29
|
+
|
|
30
|
+
# Router configuration
|
|
31
|
+
module_router: Any = get_router
|
|
32
|
+
{% if with_config %}
|
|
33
|
+
# Settings
|
|
34
|
+
module_settings: Any = {{ plugin_class }}Settings
|
|
35
|
+
{% endif %}
|
|
36
|
+
|
|
37
|
+
# Optional: Static files
|
|
38
|
+
extra_js_files: List[str] = []
|
|
39
|
+
extra_css_files: List[str] = []
|
|
40
|
+
|
|
41
|
+
# Optional: Dependencies
|
|
42
|
+
optional_dependencies: dict = {}
|
|
43
|
+
|
|
44
|
+
def on_load_complete(
|
|
45
|
+
self,
|
|
46
|
+
fast_pluggy: Annotated["FastPluggy", InjectDependency],
|
|
47
|
+
) -> None:
|
|
48
|
+
"""Called when the plugin is fully loaded."""
|
|
49
|
+
pass
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=70.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "fastpluggy-{{ plugin_name | replace('_', '-') }}"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "{{ plugin_label }} plugin for FastPluggy"
|
|
9
|
+
requires-python = ">=3.10"
|
|
10
|
+
dependencies = [
|
|
11
|
+
"FastPluggy>=0.4.0",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
[tool.setuptools]
|
|
15
|
+
packages = ["fastpluggy_plugin.{{ plugin_name }}"]
|
|
16
|
+
package-dir = { "fastpluggy_plugin.{{ plugin_name }}" = "src" }
|
|
17
|
+
include-package-data = true
|
|
18
|
+
|
|
19
|
+
[tool.setuptools.package-data]
|
|
20
|
+
"*" = ["templates/**/*.j2"]
|
|
21
|
+
|
|
22
|
+
[project.entry-points."fastpluggy.plugins"]
|
|
23
|
+
{{ plugin_name }} = "fastpluggy_plugin.{{ plugin_name }}.plugin:{{ plugin_class }}"
|
|
24
|
+
{% if with_cli_commands %}
|
|
25
|
+
|
|
26
|
+
[project.entry-points."fastpluggy.cli"]
|
|
27
|
+
{{ plugin_name | replace('_', '-') }} = "fastpluggy_plugin.{{ plugin_name }}.cli:{{ plugin_name }}_group"
|
|
28
|
+
{% endif %}
|
|
29
|
+
|
|
30
|
+
[project.optional-dependencies]
|
|
31
|
+
dev = [
|
|
32
|
+
"pytest",
|
|
33
|
+
"pytest-cov",
|
|
34
|
+
]
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# router.py
|
|
2
|
+
from fastapi import APIRouter, Request, Depends
|
|
3
|
+
from fastapi.responses import HTMLResponse
|
|
4
|
+
|
|
5
|
+
from fastpluggy.core.dependency import get_view_builder, get_fastpluggy
|
|
6
|
+
from fastpluggy.core.menu.decorator import menu_entry
|
|
7
|
+
|
|
8
|
+
# Create a router for this plugin
|
|
9
|
+
router = APIRouter(prefix="/{{ plugin_name }}", tags=["{{ plugin_label }}"])
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@menu_entry(label="{{ plugin_label }}", icon="ti ti-puzzle")
|
|
13
|
+
@router.get("/", response_class=HTMLResponse)
|
|
14
|
+
async def {{ plugin_name }}_index(
|
|
15
|
+
request: Request,
|
|
16
|
+
view_builder=Depends(get_view_builder),
|
|
17
|
+
):
|
|
18
|
+
"""Main page for {{ plugin_label }}."""
|
|
19
|
+
return view_builder.generate(
|
|
20
|
+
request,
|
|
21
|
+
title="{{ plugin_label }}",
|
|
22
|
+
widgets=[],
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@menu_entry(label="About", icon="ti ti-info-circle", parent="{{ plugin_label }}")
|
|
27
|
+
@router.get("/about", response_class=HTMLResponse)
|
|
28
|
+
async def {{ plugin_name }}_about(
|
|
29
|
+
request: Request,
|
|
30
|
+
view_builder=Depends(get_view_builder),
|
|
31
|
+
):
|
|
32
|
+
"""About page for {{ plugin_label }}."""
|
|
33
|
+
return view_builder.generate(
|
|
34
|
+
request,
|
|
35
|
+
title="About {{ plugin_label }}",
|
|
36
|
+
widgets=[],
|
|
37
|
+
)
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
# runner.py
|
|
2
|
+
import asyncio
|
|
3
|
+
import concurrent.futures
|
|
4
|
+
import logging
|
|
5
|
+
import threading
|
|
6
|
+
import time
|
|
7
|
+
import uuid
|
|
8
|
+
from datetime import datetime
|
|
9
|
+
from typing import Any, Callable, Dict, List, Optional, Union
|
|
10
|
+
|
|
11
|
+
from fastpluggy.core.database import session_scope
|
|
12
|
+
from fastpluggy.core.plugin_state import PluginState
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class TaskRunner:
|
|
16
|
+
"""Task runner for {{ plugin_name }} plugin."""
|
|
17
|
+
|
|
18
|
+
def __init__(self, fast_pluggy):
|
|
19
|
+
self.fast_pluggy = fast_pluggy
|
|
20
|
+
self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=10)
|
|
21
|
+
self.tasks = {}
|
|
22
|
+
self.running = True
|
|
23
|
+
self.lock = threading.Lock()
|
|
24
|
+
self.logger = logging.getLogger("{{ plugin_name }}.runner")
|
|
25
|
+
|
|
26
|
+
def submit(
|
|
27
|
+
self,
|
|
28
|
+
func: Callable,
|
|
29
|
+
*args,
|
|
30
|
+
task_name: Optional[str] = None,
|
|
31
|
+
task_id: Optional[str] = None,
|
|
32
|
+
allow_concurrent: bool = True,
|
|
33
|
+
max_retries: int = 0,
|
|
34
|
+
**kwargs,
|
|
35
|
+
) -> str:
|
|
36
|
+
"""Submit a task to be executed in the background."""
|
|
37
|
+
task_id = task_id or str(uuid.uuid4())
|
|
38
|
+
task_name = task_name or func.__name__
|
|
39
|
+
|
|
40
|
+
# Check if task with same name is already running
|
|
41
|
+
if not allow_concurrent:
|
|
42
|
+
with self.lock:
|
|
43
|
+
for existing_id, task_info in self.tasks.items():
|
|
44
|
+
if task_info.get("name") == task_name and task_info.get("status") == "running":
|
|
45
|
+
self.logger.warning(f"Task {task_name} is already running with ID {existing_id}")
|
|
46
|
+
return existing_id
|
|
47
|
+
|
|
48
|
+
# Create task context
|
|
49
|
+
task_context = {
|
|
50
|
+
"id": task_id,
|
|
51
|
+
"name": task_name,
|
|
52
|
+
"func": func,
|
|
53
|
+
"args": args,
|
|
54
|
+
"kwargs": kwargs,
|
|
55
|
+
"status": "pending",
|
|
56
|
+
"start_time": None,
|
|
57
|
+
"end_time": None,
|
|
58
|
+
"result": None,
|
|
59
|
+
"error": None,
|
|
60
|
+
"retries": 0,
|
|
61
|
+
"max_retries": max_retries,
|
|
62
|
+
"allow_concurrent": allow_concurrent,
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
# Store task in database
|
|
66
|
+
try:
|
|
67
|
+
from .models.context import TaskContextDB
|
|
68
|
+
|
|
69
|
+
with session_scope() as db:
|
|
70
|
+
db_task = TaskContextDB(
|
|
71
|
+
task_id=task_id,
|
|
72
|
+
task_name=task_name,
|
|
73
|
+
status="pending",
|
|
74
|
+
created_at=datetime.now(),
|
|
75
|
+
)
|
|
76
|
+
db.add(db_task)
|
|
77
|
+
except Exception as e:
|
|
78
|
+
self.logger.error(f"Failed to store task in database: {e}")
|
|
79
|
+
|
|
80
|
+
# Submit task to executor
|
|
81
|
+
with self.lock:
|
|
82
|
+
self.tasks[task_id] = task_context
|
|
83
|
+
future = self.executor.submit(self._run_task, task_id)
|
|
84
|
+
task_context["future"] = future
|
|
85
|
+
|
|
86
|
+
return task_id
|
|
87
|
+
|
|
88
|
+
def _run_task(self, task_id: str) -> Any:
|
|
89
|
+
"""Run a task and handle its result."""
|
|
90
|
+
with self.lock:
|
|
91
|
+
task_info = self.tasks.get(task_id)
|
|
92
|
+
if not task_info:
|
|
93
|
+
self.logger.error(f"Task {task_id} not found")
|
|
94
|
+
return None
|
|
95
|
+
|
|
96
|
+
task_info["status"] = "running"
|
|
97
|
+
task_info["start_time"] = datetime.now()
|
|
98
|
+
|
|
99
|
+
func = task_info["func"]
|
|
100
|
+
args = task_info["args"]
|
|
101
|
+
kwargs = task_info["kwargs"]
|
|
102
|
+
task_name = task_info["name"]
|
|
103
|
+
|
|
104
|
+
# Update task status in database
|
|
105
|
+
try:
|
|
106
|
+
from .models.context import TaskContextDB
|
|
107
|
+
|
|
108
|
+
with session_scope() as db:
|
|
109
|
+
db_task = db.query(TaskContextDB).filter_by(task_id=task_id).first()
|
|
110
|
+
if db_task:
|
|
111
|
+
db_task.status = "running"
|
|
112
|
+
db_task.started_at = datetime.now()
|
|
113
|
+
except Exception as e:
|
|
114
|
+
self.logger.error(f"Failed to update task status in database: {e}")
|
|
115
|
+
|
|
116
|
+
try:
|
|
117
|
+
self.logger.info(f"Running task {task_name} with ID {task_id}")
|
|
118
|
+
result = func(*args, **kwargs)
|
|
119
|
+
|
|
120
|
+
with self.lock:
|
|
121
|
+
task_info["status"] = "completed"
|
|
122
|
+
task_info["end_time"] = datetime.now()
|
|
123
|
+
task_info["result"] = result
|
|
124
|
+
|
|
125
|
+
# Update task status in database
|
|
126
|
+
try:
|
|
127
|
+
from .models.context import TaskContextDB
|
|
128
|
+
|
|
129
|
+
with session_scope() as db:
|
|
130
|
+
db_task = db.query(TaskContextDB).filter_by(task_id=task_id).first()
|
|
131
|
+
if db_task:
|
|
132
|
+
db_task.status = "completed"
|
|
133
|
+
db_task.completed_at = datetime.now()
|
|
134
|
+
except Exception as e:
|
|
135
|
+
self.logger.error(f"Failed to update task status in database: {e}")
|
|
136
|
+
|
|
137
|
+
return result
|
|
138
|
+
except Exception as e:
|
|
139
|
+
self.logger.error(f"Task {task_name} failed: {e}", exc_info=True)
|
|
140
|
+
|
|
141
|
+
with self.lock:
|
|
142
|
+
task_info["status"] = "failed"
|
|
143
|
+
task_info["end_time"] = datetime.now()
|
|
144
|
+
task_info["error"] = str(e)
|
|
145
|
+
task_info["retries"] += 1
|
|
146
|
+
|
|
147
|
+
# Update task status in database
|
|
148
|
+
try:
|
|
149
|
+
from .models.context import TaskContextDB
|
|
150
|
+
|
|
151
|
+
with session_scope() as db:
|
|
152
|
+
db_task = db.query(TaskContextDB).filter_by(task_id=task_id).first()
|
|
153
|
+
if db_task:
|
|
154
|
+
db_task.status = "failed"
|
|
155
|
+
db_task.error = str(e)
|
|
156
|
+
db_task.completed_at = datetime.now()
|
|
157
|
+
except Exception as db_error:
|
|
158
|
+
self.logger.error(f"Failed to update task status in database: {db_error}")
|
|
159
|
+
|
|
160
|
+
# Retry if needed
|
|
161
|
+
if task_info["retries"] <= task_info["max_retries"] or task_info["max_retries"] < 0:
|
|
162
|
+
self.logger.info(f"Retrying task {task_name} ({task_info['retries']}/{task_info['max_retries']})")
|
|
163
|
+
return self._run_task(task_id)
|
|
164
|
+
|
|
165
|
+
return None
|
|
166
|
+
|
|
167
|
+
def graceful_shutdown(self):
|
|
168
|
+
"""Shutdown the task runner gracefully."""
|
|
169
|
+
self.logger.info("Shutting down task runner")
|
|
170
|
+
self.running = False
|
|
171
|
+
self.executor.shutdown(wait=True)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# tasks package
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# tasks/maintenance.py
|
|
2
|
+
import logging
|
|
3
|
+
from datetime import datetime, timedelta
|
|
4
|
+
|
|
5
|
+
from sqlalchemy import and_, or_
|
|
6
|
+
|
|
7
|
+
from fastpluggy.core.database import session_scope
|
|
8
|
+
from ..config import TasksRunnerSettings
|
|
9
|
+
from ..models.context import TaskContextDB
|
|
10
|
+
from ..models.report import TaskReportDB
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def purge_old_tasks():
|
|
14
|
+
"""Purge old task records from the database."""
|
|
15
|
+
logger = logging.getLogger("{{ plugin_name }}.maintenance")
|
|
16
|
+
settings = TasksRunnerSettings()
|
|
17
|
+
|
|
18
|
+
logger.info(f"Purging tasks older than {settings.purge_older_than_days} days")
|
|
19
|
+
|
|
20
|
+
cutoff_date = datetime.now() - timedelta(days=settings.purge_older_than_days)
|
|
21
|
+
|
|
22
|
+
with session_scope() as db:
|
|
23
|
+
# Find old completed or failed tasks
|
|
24
|
+
old_tasks = db.query(TaskContextDB).filter(
|
|
25
|
+
and_(
|
|
26
|
+
TaskContextDB.created_at < cutoff_date,
|
|
27
|
+
or_(
|
|
28
|
+
TaskContextDB.status == "completed",
|
|
29
|
+
TaskContextDB.status == "failed"
|
|
30
|
+
)
|
|
31
|
+
)
|
|
32
|
+
).all()
|
|
33
|
+
|
|
34
|
+
task_ids = [task.task_id for task in old_tasks]
|
|
35
|
+
|
|
36
|
+
if not task_ids:
|
|
37
|
+
logger.info("No old tasks to purge")
|
|
38
|
+
return
|
|
39
|
+
|
|
40
|
+
# Delete associated reports
|
|
41
|
+
report_count = db.query(TaskReportDB).filter(
|
|
42
|
+
TaskReportDB.task_id.in_(task_ids)
|
|
43
|
+
).delete(synchronize_session=False)
|
|
44
|
+
|
|
45
|
+
# Delete the tasks
|
|
46
|
+
task_count = db.query(TaskContextDB).filter(
|
|
47
|
+
TaskContextDB.task_id.in_(task_ids)
|
|
48
|
+
).delete(synchronize_session=False)
|
|
49
|
+
|
|
50
|
+
logger.info(f"Purged {task_count} tasks and {report_count} reports")
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# tasks/plugin_update.py
|
|
2
|
+
import logging
|
|
3
|
+
import requests
|
|
4
|
+
|
|
5
|
+
from fastpluggy.core.tools.install import is_installed, get_installed_version
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def check_for_plugin_updates():
|
|
9
|
+
"""Check for updates to installed plugins."""
|
|
10
|
+
logger = logging.getLogger("{{ plugin_name }}.plugin_update")
|
|
11
|
+
|
|
12
|
+
logger.info("Checking for plugin updates")
|
|
13
|
+
|
|
14
|
+
try:
|
|
15
|
+
# Fetch available plugins from registry
|
|
16
|
+
response = requests.get("https://registry.fastpluggy.xyz/plugins.json", timeout=10)
|
|
17
|
+
response.raise_for_status()
|
|
18
|
+
available_plugins = response.json()
|
|
19
|
+
|
|
20
|
+
updates_available = []
|
|
21
|
+
|
|
22
|
+
# Check each available plugin
|
|
23
|
+
for plugin_info in available_plugins:
|
|
24
|
+
plugin_name = plugin_info.get("name")
|
|
25
|
+
latest_version = plugin_info.get("version")
|
|
26
|
+
|
|
27
|
+
if not plugin_name or not latest_version:
|
|
28
|
+
continue
|
|
29
|
+
|
|
30
|
+
# Check if plugin is installed
|
|
31
|
+
if is_installed(plugin_name):
|
|
32
|
+
current_version = get_installed_version(plugin_name)
|
|
33
|
+
|
|
34
|
+
# Compare versions
|
|
35
|
+
if current_version and current_version != latest_version:
|
|
36
|
+
logger.info(f"Update available for {plugin_name}: {current_version} -> {latest_version}")
|
|
37
|
+
updates_available.append({
|
|
38
|
+
"name": plugin_name,
|
|
39
|
+
"current_version": current_version,
|
|
40
|
+
"latest_version": latest_version
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
if updates_available:
|
|
44
|
+
logger.info(f"Found {len(updates_available)} plugin updates")
|
|
45
|
+
# Here you could trigger notifications or automatic updates
|
|
46
|
+
else:
|
|
47
|
+
logger.info("All plugins are up to date")
|
|
48
|
+
|
|
49
|
+
return updates_available
|
|
50
|
+
|
|
51
|
+
except Exception as e:
|
|
52
|
+
logger.error(f"Failed to check for plugin updates: {e}")
|
|
53
|
+
return []
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# tasks/scheduler.py
|
|
2
|
+
import logging
|
|
3
|
+
import time
|
|
4
|
+
from datetime import datetime, timedelta
|
|
5
|
+
|
|
6
|
+
import croniter
|
|
7
|
+
from sqlalchemy import or_
|
|
8
|
+
|
|
9
|
+
from fastpluggy.core.database import session_scope
|
|
10
|
+
|
|
11
|
+
from ..models.scheduled import ScheduledTaskDB
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def schedule_loop():
|
|
15
|
+
"""Main scheduler loop that runs scheduled tasks."""
|
|
16
|
+
logger = logging.getLogger("{{ plugin_name }}.scheduler")
|
|
17
|
+
logger.info("Starting scheduler loop")
|
|
18
|
+
|
|
19
|
+
while True:
|
|
20
|
+
try:
|
|
21
|
+
# Check for tasks that need to be run
|
|
22
|
+
with session_scope() as db:
|
|
23
|
+
now = datetime.now()
|
|
24
|
+
|
|
25
|
+
# Find tasks that are due to run
|
|
26
|
+
scheduled_tasks = db.query(ScheduledTaskDB).filter(
|
|
27
|
+
ScheduledTaskDB.enabled == True,
|
|
28
|
+
or_(
|
|
29
|
+
ScheduledTaskDB.next_run <= now,
|
|
30
|
+
ScheduledTaskDB.next_run == None
|
|
31
|
+
)
|
|
32
|
+
).all()
|
|
33
|
+
|
|
34
|
+
for task in scheduled_tasks:
|
|
35
|
+
logger.info(f"Running scheduled task {task.task_name}")
|
|
36
|
+
|
|
37
|
+
# Update last_run and calculate next_run
|
|
38
|
+
task.last_run = now
|
|
39
|
+
|
|
40
|
+
if task.schedule_type == "cron" and task.cron_expression:
|
|
41
|
+
cron = croniter.croniter(task.cron_expression, now)
|
|
42
|
+
task.next_run = cron.get_next(datetime)
|
|
43
|
+
elif task.schedule_type == "interval" and task.interval_seconds:
|
|
44
|
+
task.next_run = now + timedelta(seconds=task.interval_seconds)
|
|
45
|
+
|
|
46
|
+
# Run the task
|
|
47
|
+
try:
|
|
48
|
+
# Import the function
|
|
49
|
+
module_path, func_name = task.function_path.rsplit(".", 1)
|
|
50
|
+
module = __import__(module_path, fromlist=[func_name])
|
|
51
|
+
func = getattr(module, func_name)
|
|
52
|
+
|
|
53
|
+
# Get the task runner
|
|
54
|
+
from fastpluggy.core.globals import get_global
|
|
55
|
+
runner = get_global("{{ plugin_name }}")
|
|
56
|
+
|
|
57
|
+
# Submit the task
|
|
58
|
+
runner.submit(
|
|
59
|
+
func,
|
|
60
|
+
task_name=task.task_name,
|
|
61
|
+
scheduled_task_id=task.task_id,
|
|
62
|
+
**(task.parameters or {})
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
logger.info(f"Scheduled task {task.task_name} submitted")
|
|
66
|
+
except Exception as e:
|
|
67
|
+
logger.error(f"Failed to run scheduled task {task.task_name}: {e}")
|
|
68
|
+
|
|
69
|
+
# Sleep for a bit
|
|
70
|
+
time.sleep(10)
|
|
71
|
+
except Exception as e:
|
|
72
|
+
logger.error(f"Error in scheduler loop: {e}")
|
|
73
|
+
time.sleep(30) # Sleep longer on error
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fastpluggy-cli
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: A CLI tool to scaffold FastPluggy projects
|
|
5
|
+
Author: Jerome Vaillant
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Requires-Dist: click==8.3.1
|
|
8
|
+
Requires-Dist: jinja2
|
|
9
|
+
Requires-Dist: requests
|
|
10
|
+
Requires-Dist: questionary
|
|
11
|
+
Requires-Dist: uvicorn[standard]
|
|
12
|
+
Requires-Dist: fastpluggy>=0.4.15
|
|
13
|
+
Requires-Dist: fastapi
|
|
14
|
+
Provides-Extra: e2e
|
|
15
|
+
Requires-Dist: playwright; extra == "e2e"
|
|
16
|
+
Provides-Extra: dev
|
|
17
|
+
Requires-Dist: pytest==9.0.2; extra == "dev"
|
|
18
|
+
Requires-Dist: pytest-cov==7.0.0; extra == "dev"
|
|
19
|
+
Provides-Extra: ssl
|
|
20
|
+
Requires-Dist: cryptography==46.0.5; extra == "ssl"
|