Coverage for src/robot_dispatch/services/task_service.py: 95%

133 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-07 17:18 +0000

1from __future__ import annotations 

2 

3import uuid 

4from collections.abc import Sequence 

5from dataclasses import dataclass 

6from datetime import datetime 

7 

8from sqlalchemy.exc import IntegrityError 

9 

10from robot_dispatch.config import Settings 

11from robot_dispatch.db.models import Robot, Task, TaskEvent, utcnow 

12from robot_dispatch.domain.enums import RobotStatus, TaskEventKind, TaskStatus 

13from robot_dispatch.domain.state_machine import can_transition, ensure_transition, is_cancellable 

14from robot_dispatch.logging_setup import get_logger 

15from robot_dispatch.repositories.protocols import UnitOfWorkFactory 

16from robot_dispatch.services.errors import RobotNotFound, TaskConflict, TaskNotFound 

17 

18logger = get_logger("tasks") 

19 

20 

21@dataclass(frozen=True) 

22class CreateTaskCommand: 

23 type: str 

24 payload: dict 

25 priority: int = 100 

26 external_id: str | None = None 

27 max_attempts: int | None = None 

28 timeout_seconds: int | None = None 

29 

30 

31@dataclass(frozen=True) 

32class CreateTaskResult: 

33 task: Task 

34 replayed: bool 

35 

36 

37class TaskService: 

38 def __init__(self, uow_factory: UnitOfWorkFactory, settings: Settings, *, clock=utcnow) -> None: 

39 self._uow_factory = uow_factory 

40 self._settings = settings 

41 self._clock = clock 

42 

43 async def create(self, command: CreateTaskCommand) -> CreateTaskResult: 

44 """Create a task; `external_id` makes the call idempotent. 

45 

46 The unique index on `tasks.external_id` is the source of truth: if two 

47 clients race with the same external id, the loser gets the winner's task 

48 back instead of a duplicate. 

49 """ 

50 if command.external_id: 

51 async with self._uow_factory() as uow: 

52 existing = await uow.tasks.get_by_external_id(command.external_id) 

53 if existing is not None: 

54 return CreateTaskResult(task=existing, replayed=True) 

55 

56 task = Task.new( 

57 task_type=command.type, 

58 payload=command.payload, 

59 priority=command.priority, 

60 external_id=command.external_id, 

61 max_attempts=command.max_attempts or self._settings.default_max_attempts, 

62 timeout_seconds=command.timeout_seconds or self._settings.default_task_timeout_seconds, 

63 available_at=self._clock(), 

64 ) 

65 try: 

66 async with self._uow_factory() as uow: 

67 await uow.tasks.add(task) 

68 await uow.events.add( 

69 TaskEvent.new( 

70 task_id=task.id, 

71 kind=TaskEventKind.CREATED.value, 

72 to_status=task.status, 

73 message=f"task {task.type} queued", 

74 payload={ 

75 "priority": task.priority, 

76 "external_id": task.external_id, 

77 "max_attempts": task.max_attempts, 

78 }, 

79 ) 

80 ) 

81 await uow.commit() 

82 except IntegrityError: 

83 if not command.external_id: 

84 raise 

85 async with self._uow_factory() as uow: 

86 existing = await uow.tasks.get_by_external_id(command.external_id) 

87 if existing is None: # pragma: no cover - unique violation without a row 

88 raise 

89 logger.info("task creation replayed after unique violation", external_id=command.external_id) 

90 return CreateTaskResult(task=existing, replayed=True) 

91 

92 logger.info("task created", task_id=str(task.id), type=task.type, priority=task.priority) 

93 return CreateTaskResult(task=task, replayed=False) 

94 

95 async def get(self, task_id: uuid.UUID) -> Task: 

96 async with self._uow_factory() as uow: 

97 task = await uow.tasks.get(task_id) 

98 if task is None: 

99 raise TaskNotFound(task_id) 

100 return task 

101 

102 async def list( 

103 self, 

104 *, 

105 statuses: list[str] | None = None, 

106 robot_id: uuid.UUID | None = None, 

107 task_type: str | None = None, 

108 limit: int = 50, 

109 offset: int = 0, 

110 ) -> Sequence[Task]: 

111 async with self._uow_factory() as uow: 

112 return await uow.tasks.list( 

113 statuses=statuses, 

114 robot_id=robot_id, 

115 task_type=task_type, 

116 limit=limit, 

117 offset=offset, 

118 ) 

119 

120 async def events(self, task_id: uuid.UUID) -> Sequence[TaskEvent]: 

121 async with self._uow_factory() as uow: 

122 return await uow.events.list_for_task(task_id) 

123 

124 async def stats(self) -> dict[str, int]: 

125 async with self._uow_factory() as uow: 

126 return await uow.tasks.count_by_status() 

127 

128 async def cancel(self, task_id: uuid.UUID) -> Task: 

129 now = self._clock() 

130 async with self._uow_factory() as uow: 

131 task = await uow.tasks.get(task_id) 

132 if task is None: 

133 raise TaskNotFound(task_id) 

134 current = TaskStatus(task.status) 

135 if current.is_terminal: 

136 raise TaskConflict(task_id, current.value, "task already finished") 

137 if not is_cancellable(current): 

138 raise TaskConflict( 

139 task_id, 

140 current.value, 

141 "running tasks cannot be cancelled from the API: the robot owns the execution", 

142 ) 

143 if not can_transition(current, TaskStatus.CANCELLED): # pragma: no cover - guard 

144 raise TaskConflict(task_id, current.value, "cancellation is not allowed") 

145 

146 robot: Robot | None = await uow.robots.get(task.robot_id) if task.robot_id else None 

147 if robot is not None: 

148 robot.status = RobotStatus.IDLE.value 

149 robot.current_task_id = None 

150 robot.updated_at = now 

151 

152 task.status = ensure_transition(current, TaskStatus.CANCELLED).value 

153 task.lease_expires_at = None 

154 task.finished_at = now 

155 task.updated_at = now 

156 task.version += 1 

157 await uow.events.add( 

158 TaskEvent.new( 

159 task_id=task.id, 

160 kind=TaskEventKind.CANCELLED.value, 

161 from_status=current.value, 

162 to_status=task.status, 

163 robot_id=task.robot_id, 

164 message="cancelled by API request", 

165 ) 

166 ) 

167 await uow.commit() 

168 return task 

169 

170 

171class RobotService: 

172 def __init__(self, uow_factory: UnitOfWorkFactory, *, clock=utcnow) -> None: 

173 self._uow_factory = uow_factory 

174 self._clock = clock 

175 

176 async def register( 

177 self, 

178 *, 

179 name: str, 

180 namespace: str, 

181 capabilities: list[str], 

182 ) -> tuple[Robot, bool]: 

183 """Register or refresh a robot. Registration is idempotent by name.""" 

184 now = self._clock() 

185 async with self._uow_factory() as uow: 

186 robot = await uow.robots.get_by_name(name) 

187 created = robot is None 

188 if robot is None: 

189 robot = Robot.new( 

190 name=name, 

191 namespace=namespace, 

192 capabilities=capabilities, 

193 status=RobotStatus.IDLE, 

194 last_seen_at=now, 

195 ) 

196 await uow.robots.add(robot) 

197 else: 

198 robot.namespace = namespace 

199 robot.set_capabilities(capabilities) 

200 robot.last_seen_at = now 

201 robot.updated_at = now 

202 if robot.current_task_id is None: 

203 robot.status = RobotStatus.IDLE.value 

204 await uow.commit() 

205 logger.info("robot registered", robot=name, created=created, capabilities=capabilities) 

206 return robot, created 

207 

208 async def get(self, robot_id: uuid.UUID) -> Robot: 

209 async with self._uow_factory() as uow: 

210 robot = await uow.robots.get(robot_id) 

211 if robot is None: 

212 raise RobotNotFound(robot_id) 

213 return robot 

214 

215 async def list(self) -> list[Robot]: 

216 async with self._uow_factory() as uow: 

217 return await uow.robots.list() 

218 

219 async def mark_offline(self, older_than: datetime) -> int: 

220 """Reaper helper: robots that stopped sending heartbeats become offline.""" 

221 async with self._uow_factory() as uow: 

222 robots = await uow.robots.list() 

223 touched = 0 

224 for robot in robots: 

225 if robot.status == RobotStatus.IDLE.value and ( 

226 robot.last_seen_at is None or robot.last_seen_at < older_than 

227 ): 

228 robot.status = RobotStatus.OFFLINE.value 

229 robot.updated_at = older_than 

230 touched += 1 

231 if touched: 

232 await uow.commit() 

233 return touched 

234 

235 

236def _event(task: Task, kind: TaskEventKind, **kwargs) -> TaskEvent: # pragma: no cover - helper 

237 return TaskEvent.new(task_id=task.id, kind=kind.value, **kwargs)