Debian Codegraph @

src/globus_sdk/services/timers/data.py

raw
1 from __future__ import annotations
2
3 # the name "datetime" is used in this module, so use an alternative name
4 # in order to avoid name shadowing
5 import datetime as dt
6 import logging
7 import typing as t
8 import uuid
9
10 from globus_sdk._missing import MISSING, MissingType
11 from globus_sdk._payload import GlobusPayload
12 from globus_sdk.services.transfer import TransferData
13
14 log = logging.getLogger(__name__)
15
16
17 class TransferTimer(GlobusPayload):
18 """
19 A helper for defining a payload for Transfer Timer creation.
20 Use this along with :meth:`create_timer <globus_sdk.TimersClient.create_timer>` to
21 create a timer.
22
23 .. note::
24 ``TimersClient`` has two methods for creating timers, ``create_timer`` and
25 ``create_job``.
26 ``create_job`` uses a different API -- only ``create_timer`` will work with
27 this helper class.
28
29 Users are strongly recommended to use ``create_timer`` and this helper for
30 timer creation.
31
32 :param name: A name to identify this timer
33 :param schedule: The schedule on which the timer runs
34 :param body: A transfer payload for the timer to use. If it includes
35 ``submission_id`` or ``skip_activation_check``, these parameters will be
36 removed, as they are not supported in timers.
37
38 The ``schedule`` field determines when the timer will run.
39 Timers may be "run once" or "recurring", and "recurring" timers may specify an end
40 date or a number of executions after which the timer will stop. A ``schedule`` is
41 specified as a dict, but the SDK provides two useful helpers for constructing these
42 data.
43
44 **Example Schedules**
45
46 .. tab-set::
47
48 .. tab-item:: Run Once, Right Now
49
50 .. code-block:: python
51
52 schedule = OnceTimerSchedule()
53
54 .. tab-item:: Run Once, At a Specific Time
55
56 .. code-block:: python
57
58 schedule = OnceTimerSchedule(datetime="2023-09-22T00:00:00Z")
59
60 .. tab-item:: Run Every 5 Minutes, Until a Specific Time
61
62 .. code-block:: python
63
64 schedule = RecurringTimerSchedule(
65 interval_seconds=300,
66 end={"condition": "time", "datetime": "2023-10-01T00:00:00Z"},
67 )
68
69 .. tab-item:: Run Every 30 Minutes, 10 Times
70
71 .. code-block:: python
72
73 schedule = RecurringTimerSchedule(
74 interval_seconds=1800,
75 end={"condition": "iterations", "iterations": 10},
76 )
77
78 .. tab-item:: Run Every 10 Minutes, Indefinitely
79
80 .. code-block:: python
81
82 schedule = RecurringTimerSchedule(interval_seconds=600)
83
84 Using these schedules, you can create a timer from a ``TransferData`` object:
85
86 .. code-block:: pycon
87
88 >>> from globus_sdk import TransferData, TransferTimer
89 >>> schedule = ...
90 >>> transfer_data = TransferData(...)
91 >>> timer = TransferTimer(
92 ... name="my timer",
93 ... schedule=schedule,
94 ... body=transfer_data,
95 ... )
96
97 Submit the timer to the Timers service with
98 :meth:`create_timer <globus_sdk.TimersClient.create_timer>`.
99 """
100
101 def __init__(
102 self,
103 *,
104 name: str | MissingType = MISSING,
105 schedule: dict[str, t.Any] | RecurringTimerSchedule | OnceTimerSchedule,
106 body: dict[str, t.Any] | TransferData,
107 ) -> None:
108 super().__init__()
109 self["timer_type"] = "transfer"
110 self["name"] = name
111 self["schedule"] = schedule
112 self["body"] = self._preprocess_body(body)
113
114 def _preprocess_body(
115 self, body: dict[str, t.Any] | TransferData
116 ) -> dict[str, t.Any]:
117 # shallow-copy for dicts, convert any TransferData to a dict
118 new_body = dict(body)
119 # remove the skip_activation_check and submission_id parameters unconditionally
120 # (not supported in timers, but often present in TransferData)
121 new_body.pop("submission_id", None)
122 new_body.pop("skip_activation_check", None)
123 return new_body
124
125
126 class FlowTimer(GlobusPayload):
127 """
128 A helper for defining a payload for Flow Timer creation.
129 Use this along with :meth:`create_timer <globus_sdk.TimersClient.create_timer>` to
130 create a timer.
131
132 .. note::
133
134 ``TimersClient`` has two methods for creating timers:
135 ``create_timer`` and ``create_job``.
136
137 This helper class only works with the ``create_timer`` method.
138
139 :param flow_id: The flow ID to run when the timer runs.
140 :param name: A name to identify this timer.
141 :param schedule: The schedule on which the timer runs
142 :param body: A transfer payload for the timer to use.
143
144 The ``schedule`` field determines when the timer will run.
145 Timers may be "run once" or "recurring", and "recurring" timers may specify an end
146 date or the number of executions after which the timer will stop.
147 A ``schedule`` is specified as a dict, but the SDK provides two helpers
148 for constructing these data.
149
150 **Example Schedules**
151
152 .. tab-set::
153
154 .. tab-item:: Run Once, Right Now
155
156 .. code-block:: python
157
158 schedule = OnceTimerSchedule()
159
160 .. tab-item:: Run Once, At a Specific Time
161
162 .. code-block:: python
163
164 schedule = OnceTimerSchedule(datetime="2023-09-22T00:00:00Z")
165
166 .. tab-item:: Run Every 5 Minutes, Until a Specific Time
167
168 .. code-block:: python
169
170 schedule = RecurringTimerSchedule(
171 interval_seconds=300,
172 end={"condition": "time", "datetime": "2023-10-01T00:00:00Z"},
173 )
174
175 .. tab-item:: Run Every 30 Minutes, 10 Times
176
177 .. code-block:: python
178
179 schedule = RecurringTimerSchedule(
180 interval_seconds=1800,
181 end={"condition": "iterations", "iterations": 10},
182 )
183
184 .. tab-item:: Run Every 10 Minutes, Indefinitely
185
186 .. code-block:: python
187
188 schedule = RecurringTimerSchedule(interval_seconds=600)
189
190 Using these schedules, you can create a timer:
191
192 .. code-block:: pycon
193
194 >>> from globus_sdk import FlowTimer
195 >>> schedule = ...
196 >>> timer = FlowTimer(
197 ... name="my timer",
198 ... flow_id="00000000-19a9-44e6-9c1a-867da59d84ab",
199 ... schedule=schedule,
200 ... body={
201 ... "body": {
202 ... "input_key": "input_value",
203 ... },
204 ... "run_managers": [
205 ... "urn:globus:auth:identity:11111111-be6a-473a-a027-4cfe4ceeafe3"
206 ... ],
207 ... },
208 ... )
209
210 Submit the timer to the Timers service with
211 :meth:`create_timer <globus_sdk.TimersClient.create_timer>`.
212 """
213
214 def __init__(
215 self,
216 *,
217 flow_id: uuid.UUID | str,
218 name: str | MissingType = MISSING,
219 schedule: dict[str, t.Any] | RecurringTimerSchedule | OnceTimerSchedule,
220 body: dict[str, t.Any],
221 ) -> None:
222 super().__init__()
223 self["timer_type"] = "flow"
224 self["flow_id"] = flow_id
225 self["name"] = name
226 self["schedule"] = schedule
227 self["body"] = self._preprocess_body(body)
228
229 def _preprocess_body(self, body: dict[str, t.Any]) -> dict[str, t.Any]:
230 # Additional processing may be added in the future.
231 return body.copy()
232
233
234 class RecurringTimerSchedule(GlobusPayload):
235 """
236 A helper used as part of a *timer* to define when the *timer* will run.
237
238 A ``RecurringTimerSchedule`` is used to describe a *timer* which runs repeatedly
239 until some end condition is reached.
240
241 :param interval_seconds: The number of seconds between each run of the timer.
242 :param start: The time at which to start the timer, either as an ISO 8601 string
243 with timezone information, or as a ``datetime.datetime`` object.
244 :param end: The end condition for the timer, as a dict. This either expresses a
245 number of iterations for the timer or an end date.
246
247 Example ``end`` conditions:
248
249 .. code-block:: python
250
251 # run 10 times
252 end = {"condition": "iterations", "iterations": 10}
253
254 # run until a specific date
255 end = {"condition": "time", "datetime": "2023-10-01T00:00:00Z"}
256
257 If the end condition is ``time``, then the ``datetime`` value can be expressed as a
258 python ``datetime`` type as well, e.g.
259
260 .. code-block:: python
261
262 # end in 10 days
263 end = {
264 "condition": "time",
265 "datetime": datetime.datetime.now() + datetime.timedelta(days=10),
266 }
267 """
268
269 def __init__(
270 self,
271 interval_seconds: int,
272 start: str | dt.datetime | MissingType = MISSING,
273 end: dict[str, t.Any] | MissingType = MISSING,
274 ) -> None:
275 super().__init__()
276 self["type"] = "recurring"
277 self["interval_seconds"] = interval_seconds
278 self["start"] = _format_date(start)
279 self["end"] = end
280
281 # if a datetime is given for part of the end condition, format it (and
282 # shallow-copy the end condition)
283 # primarily, this handles
284 # end={"condition": "time", "datetime": <some-datetime>}
285 if isinstance(end, dict):
286 self["end"] = {
287 k: (_format_date(v) if isinstance(v, dt.datetime) else v)
288 for k, v in end.items()
289 }
290
291
292 class OnceTimerSchedule(GlobusPayload):
293 """
294 A helper used as part of a *timer* to define when the *timer* will run.
295
296 A ``OnceTimerSchedule`` is used to describe a *timer* which runs exactly once.
297 It may be scheduled for a time in the future.
298
299 :param datetime: The time at which to run the timer, either as an ISO 8601
300 string with timezone information, or as a ``datetime.datetime`` object.
301 """
302
303 def __init__(
304 self,
305 datetime: str | dt.datetime | MissingType = MISSING,
306 ) -> None:
307 super().__init__()
308 self["type"] = "once"
309 self["datetime"] = _format_date(datetime)
310
311
312 class TimerJob(GlobusPayload):
313 r"""
314 .. warning::
315
316 This method of specifying and creating Timers for data transfer is now
317 deprecated. Users should use ``TimerData`` instead.
318
319 ``TimerJob`` is still supported for non-transfer use-cases.
320
321 Helper for creating a timer in the Timers service. Used as the ``data``
322 argument in :meth:`create_job <globus_sdk.TimersClient.create_job>`.
323
324 The ``callback_url`` parameter should always be the URL used to run an
325 action provider.
326
327 :param callback_url: URL for the action which the Timers job will use.
328 :param callback_body: JSON data which Timers will send to the Action Provider on
329 each invocation
330 :param start: The datetime at which to start the Timers job.
331 :param interval: The interval at which the Timers job should recur. Interpreted as
332 seconds if specified as an integer. If ``stop_after_n == 1``, i.e. the job is
333 set to run only a single time, then interval *must* be None.
334 :param name: A (not necessarily unique) name to identify this job in Timers
335 :param stop_after: A date after which the Timers job will stop running
336 :param stop_after_n: A number of executions after which the Timers job will stop
337 :param scope: Timers defaults to the Transfer 'all' scope. Use this parameter to
338 change the scope used by Timers when calling the Transfer Action Provider.
339
340 .. automethodlist:: globus_sdk.TimerJob
341 """
342
343 def __init__(
344 self,
345 callback_url: str,
346 callback_body: dict[str, t.Any],
347 start: dt.datetime | str,
348 interval: dt.timedelta | int | None,
349 *,
350 name: str | None = None,
351 stop_after: dt.datetime | None = None,
352 stop_after_n: int | None = None,
353 scope: str | None = None,
354 ) -> None:
355 super().__init__()
356 self["callback_url"] = callback_url
357 self["callback_body"] = callback_body
358 if isinstance(start, dt.datetime):
359 self["start"] = start.isoformat()
360 else:
361 self["start"] = start
362 if isinstance(interval, dt.timedelta):
363 self["interval"] = int(interval.total_seconds())
364 else:
365 self["interval"] = interval
366 if name is not None:
367 self["name"] = name
368 if stop_after is not None:
369 self["stop_after"] = stop_after.isoformat()
370 if stop_after_n is not None:
371 self["stop_after_n"] = stop_after_n
372 if scope is not None:
373 self["scope"] = scope
374
375
376 def _format_date(date: str | dt.datetime | MissingType) -> str | MissingType:
377 if isinstance(date, dt.datetime):
378 if date.tzinfo is None:
379 date = date.astimezone(dt.timezone.utc)
380 return date.isoformat(timespec="seconds")
381 else:
382 return date