Python functions as REST objects, with clustering, load balancing and state replication; no containers or orchestration.

0 downloads

Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-primitive.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-primitive.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-primitive.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Dan Q Consolidate duplicate QUICKSTARTs on the top-level file 503f830 7 months ago History
scheduler.py · 5.4 KB · 211 lines
1"""
2Scheduler Object - REST API for managing scheduled tasks
3
4This object can be executed via HTTP to create, list, and cancel scheduled tasks.
5The actual execution happens in daemon.py (background process).
6
7Example usage:
8 # Create cron task (every 6 hours)
9 POST /objects/scheduler
10 {
11 "object_id": "cleanup",
12 "schedule": "0 */6 * * *",
13 "payload": {"max_age_days": 30}
14 }
15
16 # Create one-time task
17 POST /objects/scheduler
18 {
19 "object_id": "report_generator",
20 "schedule": "2025-12-01T14:30:00Z",
21 "payload": {"report_type": "monthly"}
22 }
23
24 # List all scheduled tasks
25 GET /objects/scheduler
26
27 # Cancel task
28 DELETE /objects/scheduler?task_id=abc123
29"""
30
31import time
32import json
33import secrets
34from pathlib import Path
35from typing import Any, Dict, List, Optional
36from datetime import datetime
37
38# These will be injected by ObjectRuntime
39_logger = None
40_state_manager = None
41
42
43def POST(request: Dict[str, Any]) -> Dict[str, Any]:
44 """Create scheduled task"""
45 object_id = request.get('object_id', '').strip()
46 method = request.get('method', 'POST')
47 schedule = request.get('schedule', '').strip()
48 payload = request.get('payload', {})
49
50 if not object_id:
51 return {'status': 'error', 'message': 'object_id is required'}
52
53 if not schedule:
54 return {'status': 'error', 'message': 'schedule is required'}
55
56 # Determine task type (cron vs one-time)
57 task_type = _determine_task_type(schedule)
58
59 if task_type == 'invalid':
60 return {'status': 'error', 'message': f'Invalid schedule format: {schedule}'}
61
62 # Create task
63 task_id = secrets.token_hex(8)
64 task = {
65 'id': task_id,
66 'object_id': object_id,
67 'method': method,
68 'schedule': schedule,
69 'payload': payload,
70 'type': task_type,
71 'created_at': int(time.time()),
72 'last_run': None,
73 'next_run': None, # Will be calculated by daemon
74 'run_count': 0,
75 'status': 'active',
76 }
77
78 # Save to state
79 _save_task(task)
80
81 if _logger:
82 _logger.info('Scheduled task created',
83 task_id=task_id,
84 object_id=object_id,
85 schedule=schedule,
86 task_type=task_type)
87
88 return {
89 'status': 'ok',
90 'task_id': task_id,
91 'message': f'Task scheduled: {schedule}',
92 }
93
94
95def GET(request: Dict[str, Any]) -> Dict[str, Any]:
96 """List scheduled tasks or get specific task"""
97 task_id = request.get('task_id')
98
99 if task_id:
100 # Get specific task
101 task = _get_task(task_id)
102 if not task:
103 return {'status': 'error', 'message': f'Task not found: {task_id}'}
104 return {'status': 'ok', 'task': task}
105
106 else:
107 # List all tasks
108 tasks = _get_all_tasks()
109
110 # Filter by status if requested
111 status_filter = request.get('status')
112 if status_filter:
113 tasks = [t for t in tasks if t.get('status') == status_filter]
114
115 return {
116 'status': 'ok',
117 'tasks': tasks,
118 'count': len(tasks),
119 }
120
121
122def DELETE(request: Dict[str, Any]) -> Dict[str, Any]:
123 """Cancel scheduled task"""
124 task_id = request.get('task_id', '').strip()
125
126 if not task_id:
127 return {'status': 'error', 'message': 'task_id is required'}
128
129 task = _get_task(task_id)
130 if not task:
131 return {'status': 'error', 'message': f'Task not found: {task_id}'}
132
133 # Mark as cancelled
134 task['status'] = 'cancelled'
135 task['cancelled_at'] = int(time.time())
136 _save_task(task)
137
138 if _logger:
139 _logger.info('Scheduled task cancelled', task_id=task_id)
140
141 return {
142 'status': 'ok',
143 'message': f'Task cancelled: {task_id}',
144 }
145
146
147# Helper functions
148
149def _determine_task_type(schedule: str) -> str:
150 """Determine if schedule is cron or one-time"""
151 # Check if it looks like ISO timestamp (one-time)
152 if 'T' in schedule or schedule.count('-') >= 2:
153 try:
154 # Try parsing as ISO datetime
155 datetime.fromisoformat(schedule.replace('Z', '+00:00'))
156 return 'onetime'
157 except:
158 pass
159
160 # Check if it looks like cron (5 or 6 fields separated by spaces)
161 parts = schedule.split()
162 if len(parts) in [5, 6]:
163 # Basic cron syntax check
164 try:
165 from croniter import croniter
166 croniter(schedule) # Will raise if invalid
167 return 'cron'
168 except:
169 pass
170
171 return 'invalid'
172
173
174def _save_task(task: Dict[str, Any]) -> None:
175 """Save task to state"""
176 if not _state_manager:
177 return
178
179 task_id = task['id']
180 _state_manager.set(f'task_{task_id}', json.dumps(task))
181
182
183def _get_task(task_id: str) -> Optional[Dict[str, Any]]:
184 """Get task from state"""
185 if not _state_manager:
186 return None
187
188 task_json = _state_manager.get(f'task_{task_id}')
189 if not task_json:
190 return None
191
192 return json.loads(task_json)
193
194
195def _get_all_tasks() -> List[Dict[str, Any]]:
196 """Get all tasks from state"""
197 if not _state_manager:
198 return []
199
200 tasks = []
201 all_state = _state_manager.get_all()
202
203 for key, value in all_state.items():
204 if key.startswith('task_'):
205 task = json.loads(value)
206 tasks.append(task)
207
208 # Sort by created_at (newest first)
209 tasks.sort(key=lambda t: t.get('created_at', 0), reverse=True)
210
211 return tasks