Coverage for src / orcheo / triggers / layer / cron.py: 98%

85 statements  

« prev     ^ index     » next       coverage.py v7.13.0, created at 2026-11-16 14:04 +0000

1"""Cron trigger helpers for the trigger layer.""" 

2 

3from __future__ import annotations 1st

4from datetime import UTC, datetime 1st

5from uuid import UUID 1st

6from orcheo.triggers.cron import CronTriggerConfig, CronTriggerState 1st

7from orcheo.triggers.layer.models import CronDispatchPlan 1st

8from orcheo.triggers.layer.state import TriggerLayerState 1st

9 

10 

11class CronTriggerMixin(TriggerLayerState): 1st

12 """Provide cron trigger orchestration helpers.""" 

13 

14 def configure_cron( 1st

15 self, 

16 workflow_id: UUID, 

17 config: CronTriggerConfig, 

18 *, 

19 last_dispatched_at: datetime | None = None, 

20 ) -> CronTriggerConfig: 

21 """Persist cron configuration for the workflow and return a copy. 

22 

23 Args: 

24 workflow_id: The workflow identifier. 

25 config: The cron trigger configuration. 

26 last_dispatched_at: Optional datetime of the last successful dispatch. 

27 Used to correctly compute the next fire time after worker restarts. 

28 """ 

29 existing_state = self._cron_states.get(workflow_id) 1wNOPbghQiueEjcdmqkxG!#$%RWKMvXYZy'H(SznloApfr0TUBFCaV)I

30 if existing_state is None: 1wNOPbghQiueEjcdmqkxG!#$%RWKMvXYZy'H(SznloApfr0TUBFCaV)I

31 state = CronTriggerState(config, last_dispatched_at=last_dispatched_at) 1wNOPbghQiueEjcdmqkxG!#$%RWKMvXYZy'H(SznloApfr0TUBFCaV)I

32 self._cron_states[workflow_id] = state 1wNOPbghQiueEjcdmqkxG!#$%RWKMvXYZy'H(SznloApfr0TUBFCaV)I

33 else: 

34 existing_state.update_config(config, last_dispatched_at=last_dispatched_at) 1wv

35 state = existing_state 1wv

36 return state.config 1wNOPbghQiueEjcdmqkxG!#$%RWKMvXYZy'H(SznloApfr0TUBFCaV)I

37 

38 def get_cron_config(self, workflow_id: UUID) -> CronTriggerConfig | None: 1st

39 """Return the stored cron configuration or None if not configured.""" 

40 state = self._cron_states.get(workflow_id) 23 [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpb4 qbrbsbtbw N 5 ubvb6 wbO 7 Q u e G W X Y Z f 0 U 8 9 D

41 if state is None: 23 [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpb4 qbrbsbtbw N 5 ubvb6 wbO 7 Q u e G W X Y Z f 0 U 8 9 D

42 return None 23 [ ] ^ _ ` { | } ~ abbbcbdbebfbgbhbibjbkblbmbnbobpb4 qbrbsbtbw N 5 ubvb6 wbO 7 Q u U 8 9 D

43 return state.config 1wNOQeGWXYZf0U

44 

45 def get_cron_last_dispatched_at(self, workflow_id: UUID) -> datetime | None: 1st

46 """Return the last dispatch time for the workflow or None if not set.""" 

47 state = self._cron_states.get(workflow_id) 2xb

48 if state is None: 48 ↛ 50line 48 didn't jump to line 50 because the condition on line 48 was always true2xb

49 return None 2xb

50 return state.last_dispatched_at 

51 

52 def remove_cron_config(self, workflow_id: UUID) -> bool: 1st

53 """Remove cron configuration state for the workflow if present.""" 

54 removed = self._cron_states.pop(workflow_id, None) is not None 23 w 5 6 ybP zbAb7 u E Bbd q CbDbEbFbG GbHbIbR v S l r T JbKbLbMbNbObPbQbRbSb8 9 TbUbVbV

55 if removed: 23 w 5 6 ybP zbAb7 u E Bbd q CbDbEbFbG GbHbIbR v S l r T JbKbLbMbNbObPbQbRbSb8 9 TbUbVbV

56 self._cron_run_index = { 1wPuEdqGRvSlrTV

57 run_id: stored_workflow_id 

58 for run_id, stored_workflow_id in self._cron_run_index.items() 

59 if stored_workflow_id != workflow_id 

60 } 

61 return removed 23 w 5 6 ybP zbAb7 u E Bbd q CbDbEbFbG GbHbIbR v S l r T JbKbLbMbNbObPbQbRbSb8 9 TbUbVbV

62 

63 def collect_due_cron_dispatches(self, *, now: datetime) -> list[CronDispatchPlan]: 1st

64 """Return cron dispatch plans that are due at the provided reference time.""" 

65 if now is None: 1*+,bghi-ueEjcdmqkxznloApfr.B/:;=?JFa@

66 raise ValueError("now parameter cannot be None") 1@

67 

68 if now.tzinfo is None: 1*+,bghi-ueEjcdmqkxznloApfr.B/:;=?JFa

69 now = now.replace(tzinfo=UTC) 1J

70 

71 plans: list[CronDispatchPlan] = [] 1*+,bghi-ueEjcdmqkxznloApfr.B/:;=?JFa

72 for workflow_id, state in self._cron_states.items(): 1*+,bghi-ueEjcdmqkxznloApfr.B/:;=?JFa

73 try: 1bghiejcdmqkxznloApfrBJFa

74 if self._health_guard and not self._health_guard.is_workflow_healthy( 1bghiejcdmqkxznloApfrBJFa

75 workflow_id 

76 ): 

77 continue 1F

78 due_at = state.peek_due(now=now) 1bghiejcdmqkxznloApfrBJa

79 if due_at is None or not state.can_dispatch(): 1bghiejcdmqkxznloApfrBa

80 continue 1becdm

81 plans.append( 1bghiejcdqkxznloApfrBa

82 CronDispatchPlan( 

83 workflow_id=workflow_id, 

84 scheduled_for=due_at, 

85 timezone=state.config.timezone, 

86 ) 

87 ) 

88 except Exception as exc: # pragma: no cover - logging path 1J

89 self._logger.error( 1J

90 "Error checking cron dispatch for workflow %s: %s", 

91 workflow_id, 

92 exc, 

93 ) 

94 continue 1J

95 return plans 1*+,bghi-ueEjcdmqkxznloApfr.B/:;=?JFa

96 

97 def commit_cron_dispatch(self, workflow_id: UUID) -> None: 1st

98 """Advance the cron schedule after a run has been enqueued.""" 

99 if workflow_id is None: 1bghiejcdkf1aD@

100 raise ValueError("workflow_id cannot be None") 1@

101 

102 state = self._cron_states.get(workflow_id) 1bghiejcdkf1aD

103 if state is None: 1bghiejcdkf1aD

104 self._logger.warning( 1D

105 "Cannot commit cron dispatch for workflow %s: no cron state found", 

106 workflow_id, 

107 ) 

108 return 1D

109 

110 try: 1bghiejcdkf1a

111 state.consume_due() 1bghiejcdkf1a

112 except Exception as exc: # pragma: no cover - logging path 11

113 self._logger.error( 11

114 "Failed to commit cron dispatch for workflow %s: %s", 

115 workflow_id, 

116 exc, 

117 ) 

118 raise 11

119 

120 def register_cron_run(self, run_id: UUID) -> None: 1st

121 """Register a cron-triggered run so overlap guards are enforced.""" 

122 workflow_id = self._run_workflows.get(run_id) 1bghiLejcdmkyH2fCaDI

123 if workflow_id is None: 1bghiLejcdmkyH2fCaDI

124 self._logger.warning( 1D

125 "Cannot register cron run %s: workflow not tracked", 

126 run_id, 

127 ) 

128 return 1D

129 

130 self._cron_run_index[run_id] = workflow_id 1bghiLejcdmkyH2fCaI

131 

132 state = self._cron_states.get(workflow_id) 1bghiLejcdmkyH2fCaI

133 if state is None: 1bghiLejcdmkyH2fCaI

134 self._logger.warning( 1L2

135 "Cannot register cron run %s: no cron state for workflow %s", 

136 run_id, 

137 workflow_id, 

138 ) 

139 return 1L2

140 

141 try: 1bghiejcdmkyHfCaI

142 state.register_run(run_id) 1bghiejcdmkyHfCaI

143 except Exception: 1yCa

144 self._cron_run_index.pop(run_id, None) 1yCa

145 raise 1yCa

146 

147 def release_cron_run(self, run_id: UUID) -> None: 1st

148 """Release overlap tracking for the provided cron run.""" 

149 workflow_id = self._cron_run_index.pop(run_id, None) 24 b WbXbL c YbZb0b1b2b3b4b5b6b7b8ba D

150 if workflow_id is None: 24 b WbXbL c YbZb0b1b2b3b4b5b6b7b8ba D

151 return 24 WbXbYbZb0b1b2b3b4b5b6b7b8bD

152 state = self._cron_states.get(workflow_id) 1bLca

153 if state is not None: 1bLca

154 state.release_run(run_id) 1bca

155 

156 def sync_cron_active_runs(self, workflow_id: UUID, run_ids: set[UUID]) -> None: 1st

157 """Reconcile a workflow's cron overlap tracking against persisted state. 

158 

159 See CronTriggerState.sync_active_runs for why this periodic 

160 reconciliation (rather than relying solely on register/release 

161 calls) is necessary when dispatch and execution can happen in 

162 different worker processes. 

163 """ 

164 state = self._cron_states.get(workflow_id) 2K M v n l o p 9b

165 if state is None: 2K M v n l o p 9b

166 return 29b

167 state.sync_active_runs(run_ids) 1KMvnlop

168 self._cron_run_index = { 1KMvnlop

169 stored_run_id: stored_workflow_id 

170 for stored_run_id, stored_workflow_id in self._cron_run_index.items() 

171 if stored_workflow_id != workflow_id 

172 } 

173 for run_id in run_ids: 1KMvnlop

174 self._cron_run_index[run_id] = workflow_id 1K

175 

176 

177__all__ = ["CronTriggerMixin"] 1st