workflow.core 1.4.0__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.
- workflow/__init__.py +17 -0
- workflow/cli/__init__.py +0 -0
- workflow/cli/buckets.py +124 -0
- workflow/cli/configs.py +279 -0
- workflow/cli/main.py +48 -0
- workflow/cli/pipelines.py +146 -0
- workflow/cli/results.py +168 -0
- workflow/cli/run.py +283 -0
- workflow/cli/schedules.py +234 -0
- workflow/cli/workspace.py +149 -0
- workflow/daemons/__init__.py +0 -0
- workflow/daemons/audit.py +74 -0
- workflow/daemons/transfer.py +255 -0
- workflow/definitions/__init__.py +0 -0
- workflow/definitions/config.py +124 -0
- workflow/definitions/jsonschema.md +28 -0
- workflow/definitions/notify.py +91 -0
- workflow/definitions/work.py +520 -0
- workflow/definitions/workspace.py +252 -0
- workflow/examples/function.py +92 -0
- workflow/examples/sample.svg +12 -0
- workflow/examples/sample.workflow.yml +31 -0
- workflow/helpers/__init__.py +0 -0
- workflow/helpers/date.py +33 -0
- workflow/http/__init__.py +0 -0
- workflow/http/buckets.py +286 -0
- workflow/http/client.py +136 -0
- workflow/http/configs.py +165 -0
- workflow/http/context.py +170 -0
- workflow/http/pipelines.py +123 -0
- workflow/http/results.py +305 -0
- workflow/http/schedules.py +157 -0
- workflow/lifecycle/__init__.py +1 -0
- workflow/lifecycle/archive/__init__.py +102 -0
- workflow/lifecycle/archive/http.py +58 -0
- workflow/lifecycle/archive/posix.py +185 -0
- workflow/lifecycle/archive/s3.py +157 -0
- workflow/lifecycle/attempt.py +112 -0
- workflow/lifecycle/configure.py +152 -0
- workflow/lifecycle/execute.py +159 -0
- workflow/utils/__init__.py +0 -0
- workflow/utils/decorators.py +29 -0
- workflow/utils/logger.py +93 -0
- workflow/utils/prompt.py +26 -0
- workflow/utils/read.py +146 -0
- workflow/utils/renderers.py +113 -0
- workflow/utils/tmate.sh +17 -0
- workflow/utils/validate.py +198 -0
- workflow/utils/variables.py +24 -0
- workflow/utils/write.py +44 -0
- workflow/workspaces/__init__.py +0 -0
- workflow/workspaces/chimefrb.yml +48 -0
- workflow/workspaces/development.yml +48 -0
- workflow/workspaces/site-dev.yml +36 -0
- workflow_core-1.4.0.dist-info/METADATA +115 -0
- workflow_core-1.4.0.dist-info/RECORD +58 -0
- workflow_core-1.4.0.dist-info/WHEEL +4 -0
- workflow_core-1.4.0.dist-info/entry_points.txt +3 -0
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Notification Configuration."""
|
|
2
|
+
|
|
3
|
+
from typing import Any, Dict, List, Optional
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel, Field, StrictStr
|
|
6
|
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Slack(BaseSettings):
|
|
10
|
+
"""Slack Configuration.
|
|
11
|
+
|
|
12
|
+
This class is used to configure the slack notification strategy for the work.
|
|
13
|
+
|
|
14
|
+
Args:
|
|
15
|
+
BaseModel (BaseModel): Pydantic BaseModel.
|
|
16
|
+
|
|
17
|
+
Attributes:
|
|
18
|
+
channel_id (str): Slack channel to send notifications to.
|
|
19
|
+
member_ids (List[str]): Slack members to send notifications to.
|
|
20
|
+
message (str): Slack message to send notifications with.
|
|
21
|
+
results (bool): Send slack notifications with the work results.
|
|
22
|
+
products (bool): Send slack notifications with the work product links.
|
|
23
|
+
plots (bool): Send slack notifications with the work plot links.
|
|
24
|
+
blocks (Dict[str, Any]): Slack blocks to send notifications with.
|
|
25
|
+
reply (Dict[str, Any]): Status of the slack notification.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
model_config = SettingsConfigDict(
|
|
29
|
+
title="Workflow Notify Object",
|
|
30
|
+
validate_default=True,
|
|
31
|
+
validate_assignment=True,
|
|
32
|
+
validate_return=True,
|
|
33
|
+
revalidate_instances="always",
|
|
34
|
+
env_prefix="WORKFLOW_NOTIFY_SLACK_",
|
|
35
|
+
secrets_dir="/run/secrets",
|
|
36
|
+
extra="forbid",
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
channel_id: Optional[StrictStr] = Field(
|
|
40
|
+
default=None,
|
|
41
|
+
description="Slack channel to send notifications to.",
|
|
42
|
+
examples=["C01JYQZQX0Y"],
|
|
43
|
+
)
|
|
44
|
+
member_ids: Optional[List[StrictStr]] = Field(
|
|
45
|
+
default=None,
|
|
46
|
+
description="Slack members to send notifications to.",
|
|
47
|
+
examples=[["U01JYQZQX0Y"]],
|
|
48
|
+
)
|
|
49
|
+
message: Optional[StrictStr] = Field(
|
|
50
|
+
default=None,
|
|
51
|
+
description="Slack message to send notifications with.",
|
|
52
|
+
examples=["Hello World!"],
|
|
53
|
+
)
|
|
54
|
+
results: Optional[bool] = Field(
|
|
55
|
+
default=None,
|
|
56
|
+
description="Send slack notifications with the work results.",
|
|
57
|
+
)
|
|
58
|
+
products: Optional[bool] = Field(
|
|
59
|
+
default=None,
|
|
60
|
+
description="Send slack notifications with the work product links.",
|
|
61
|
+
)
|
|
62
|
+
plots: Optional[bool] = Field(
|
|
63
|
+
default=None,
|
|
64
|
+
description="Send slack notifications with the work plot links.",
|
|
65
|
+
)
|
|
66
|
+
blocks: Optional[Dict[str, Any]] = Field(
|
|
67
|
+
default=None,
|
|
68
|
+
description="Slack blocks to send notifications with.",
|
|
69
|
+
)
|
|
70
|
+
reply: Optional[Dict[str, Any]] = Field(
|
|
71
|
+
default=None,
|
|
72
|
+
description="Status of the slack notification.",
|
|
73
|
+
examples=[{"ok": True}],
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class Notify(BaseModel):
|
|
78
|
+
"""Work Object Notification Configuration.
|
|
79
|
+
|
|
80
|
+
Args:
|
|
81
|
+
BaseModel (BaseModel): Pydantic BaseModel.
|
|
82
|
+
|
|
83
|
+
Attributes:
|
|
84
|
+
slack (Slack): Send slack notifications for the work.
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
slack: Slack = Field(
|
|
88
|
+
default_factory=Slack,
|
|
89
|
+
description="Send slack notifications for the work.",
|
|
90
|
+
examples=[Slack()],
|
|
91
|
+
)
|
|
@@ -0,0 +1,520 @@
|
|
|
1
|
+
"""Workflow Work Object."""
|
|
2
|
+
|
|
3
|
+
from json import loads
|
|
4
|
+
from time import time
|
|
5
|
+
from typing import Any, Dict, List, Literal, Optional, Union
|
|
6
|
+
|
|
7
|
+
from pydantic import (
|
|
8
|
+
AliasChoices,
|
|
9
|
+
Field,
|
|
10
|
+
FilePath,
|
|
11
|
+
SecretStr,
|
|
12
|
+
field_validator,
|
|
13
|
+
model_validator,
|
|
14
|
+
)
|
|
15
|
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
16
|
+
|
|
17
|
+
from workflow import DEFAULT_WORKSPACE_PATH
|
|
18
|
+
from workflow.definitions.config import Config
|
|
19
|
+
from workflow.definitions.notify import Notify
|
|
20
|
+
from workflow.http.context import HTTPContext
|
|
21
|
+
from workflow.utils import read
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Work(BaseSettings):
|
|
25
|
+
"""Workflow Work Object.
|
|
26
|
+
|
|
27
|
+
The work object defines the lifecycle of any action to be performed.
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
BaseSettings (BaseSettings): Pydantic BaseModel with settings.
|
|
31
|
+
|
|
32
|
+
Note:
|
|
33
|
+
The selection priority for attributes in descending order is:
|
|
34
|
+
|
|
35
|
+
- Arguments passed to the `Work` Object.
|
|
36
|
+
- Environment variables with `WORKFLOW_` prefix.
|
|
37
|
+
- Variables from /run/secrets secrets directory.
|
|
38
|
+
- The default values in the class constructor.
|
|
39
|
+
|
|
40
|
+
Environemnt Prefixes:
|
|
41
|
+
|
|
42
|
+
- `WORKFLOW_` for all work attributes.
|
|
43
|
+
- `WORKFLOW_HTTP_` for all work http attributes.
|
|
44
|
+
- `WORKFLOW_CONFIG_` for all work config attributes.
|
|
45
|
+
- `WORKFLOW_NOTIFY_` for all work notify attributes.
|
|
46
|
+
|
|
47
|
+
The size of the results dictionary is limited to 4MB. If the results
|
|
48
|
+
dictionary is larger than 4MB, it is ignored and not mapped to the
|
|
49
|
+
work object. Use the `products` attribute to store large data products.
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
Attributes:
|
|
53
|
+
pipeline (str): Name of the pipeline. (Required)
|
|
54
|
+
site (str): Site where the work will be performed. (Required)
|
|
55
|
+
user (str): User who created the work. (Required)
|
|
56
|
+
|
|
57
|
+
function (str): Python function to run `function(**parameters)`.
|
|
58
|
+
parameters (Dict[str, Any]): Parameters to pass to the function.
|
|
59
|
+
command (List[str]): Command to run as `subprocess.run(command)`.
|
|
60
|
+
results (Dict[str, Any]): Results from the work.
|
|
61
|
+
products (List[str]): Data products from work.
|
|
62
|
+
plots (List[str]): Visual plots of the work.
|
|
63
|
+
tags (List[str]): Searchable tags of the work.
|
|
64
|
+
event (List[int]): Unique ID[s] the work was performed against.
|
|
65
|
+
|
|
66
|
+
id (str): BSON ID of the work, set by the database.
|
|
67
|
+
creation (float): Creation time of the work.
|
|
68
|
+
start (float): Start time of the work, set by the backend.
|
|
69
|
+
stop (float): Stop time of the work, set by the client.
|
|
70
|
+
attempt (int): Attempt number of the work. Defaults to 0.
|
|
71
|
+
status (str): Status of the work. Defaults to "created".
|
|
72
|
+
timeout (int): Timeout for the work in seconds. Defaults to 3600 seconds.
|
|
73
|
+
retries (int): Number of retries for the work. Defaults to 2 retries.
|
|
74
|
+
priority (int): Priority of the work. Defaults to 3.
|
|
75
|
+
config (Config): Configuration for the lifecycle of the work.
|
|
76
|
+
notify (Notify): Notification configuration for the work.
|
|
77
|
+
|
|
78
|
+
workspace (FilePath): Path to the active workspace configuration.
|
|
79
|
+
Defaults to `~/.config/workflow/workspace.yml`. (Excluded from payload)
|
|
80
|
+
token (SecretStr): Workflow Access Token. (Excluded from payload)
|
|
81
|
+
http (HTTPContext): HTTP Context for backends. (Excluded from payload)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
Raises:
|
|
85
|
+
ValueError: When work is invalid.
|
|
86
|
+
|
|
87
|
+
Returns:
|
|
88
|
+
Object (Work): Work object.
|
|
89
|
+
|
|
90
|
+
Example:
|
|
91
|
+
```bash
|
|
92
|
+
# Set the environment variables to override the defaults.
|
|
93
|
+
export WORKFLOW_PRIORITY=4
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
from workflow.definitions.work import Work
|
|
98
|
+
|
|
99
|
+
work = Work(pipeline="test", site="local", user="shinybrar")
|
|
100
|
+
work.dump_model()
|
|
101
|
+
{
|
|
102
|
+
"config": {...},
|
|
103
|
+
"notify": {"slack": {}},
|
|
104
|
+
"pipeline": "test-pipeline",
|
|
105
|
+
"site": "local",
|
|
106
|
+
"user": "shinybrar",
|
|
107
|
+
"timeout": 3600,
|
|
108
|
+
"retries": 2,
|
|
109
|
+
"priority": 4, # Overridden by the environment variable.
|
|
110
|
+
"attempt": 0,
|
|
111
|
+
"status": "created",
|
|
112
|
+
}
|
|
113
|
+
work.deposit(return_ids=True)
|
|
114
|
+
```
|
|
115
|
+
"""
|
|
116
|
+
|
|
117
|
+
# * Configuration for the Pydantic Model.
|
|
118
|
+
model_config = SettingsConfigDict(
|
|
119
|
+
title="Workflow Work Object",
|
|
120
|
+
validate_assignment=True,
|
|
121
|
+
validate_return=True,
|
|
122
|
+
revalidate_instances="always",
|
|
123
|
+
env_prefix="WORKFLOW_",
|
|
124
|
+
secrets_dir="/run/secrets",
|
|
125
|
+
extra="ignore",
|
|
126
|
+
json_schema_mode_override="serialization",
|
|
127
|
+
)
|
|
128
|
+
# * Runtime configurations for the Work Object, these are not part of the payload.
|
|
129
|
+
# * and describe the behavior of the work object in the current instantiation.
|
|
130
|
+
workspace: FilePath = Field(
|
|
131
|
+
default=DEFAULT_WORKSPACE_PATH,
|
|
132
|
+
validate_default=True,
|
|
133
|
+
description="Default workspace configuration filepath.",
|
|
134
|
+
examples=["/home/user/.config/workflow/workspace.yml"],
|
|
135
|
+
exclude=True,
|
|
136
|
+
)
|
|
137
|
+
token: Optional[SecretStr] = Field(
|
|
138
|
+
default=None,
|
|
139
|
+
validation_alias=AliasChoices(
|
|
140
|
+
"WORKFLOW_HTTP_TOKEN",
|
|
141
|
+
"WORKFLOW_TOKEN",
|
|
142
|
+
"GITHUB_TOKEN",
|
|
143
|
+
"GITHUB_PAT",
|
|
144
|
+
),
|
|
145
|
+
exclude=True,
|
|
146
|
+
description="Workflow Access Token.",
|
|
147
|
+
examples=["ghp_1234567890abcdefg"],
|
|
148
|
+
)
|
|
149
|
+
http: HTTPContext = Field(
|
|
150
|
+
default=None,
|
|
151
|
+
validate_default=False,
|
|
152
|
+
description="HTTP Context for backend connections.",
|
|
153
|
+
exclude=True,
|
|
154
|
+
repr=False,
|
|
155
|
+
)
|
|
156
|
+
# * Required attributes, must be provided by the user.
|
|
157
|
+
pipeline: str = Field(
|
|
158
|
+
...,
|
|
159
|
+
min_length=1,
|
|
160
|
+
max_length=128,
|
|
161
|
+
description="Name of the pipeline (required). Reformated to hyphen-case.",
|
|
162
|
+
examples=["sample-pipeline"],
|
|
163
|
+
)
|
|
164
|
+
site: str = Field(
|
|
165
|
+
...,
|
|
166
|
+
description="""
|
|
167
|
+
Site where the work will be performed (required).
|
|
168
|
+
Valid sites are defined in the workspace configuration.
|
|
169
|
+
""",
|
|
170
|
+
examples=["chime"],
|
|
171
|
+
)
|
|
172
|
+
user: str = Field(
|
|
173
|
+
...,
|
|
174
|
+
description="User ID who created the work (required).",
|
|
175
|
+
examples=["shinybrar"],
|
|
176
|
+
)
|
|
177
|
+
# * Optional attributes, can be provided by the user.
|
|
178
|
+
function: Optional[str] = Field(
|
|
179
|
+
default=None,
|
|
180
|
+
description="""
|
|
181
|
+
Name of the Python function to run as `function(**parameters)`,
|
|
182
|
+
Only either `function` or `command` can be provided.
|
|
183
|
+
""",
|
|
184
|
+
examples=["workflow.example.mean"],
|
|
185
|
+
)
|
|
186
|
+
parameters: Optional[Dict[str, Any]] = Field(
|
|
187
|
+
default=None,
|
|
188
|
+
description="""
|
|
189
|
+
Parameters to pass the pipeline function. Equivalent to
|
|
190
|
+
running `function(**parameters)`. Ignored if `command` is set.
|
|
191
|
+
""",
|
|
192
|
+
examples=[{"a": 1, "b": 2}],
|
|
193
|
+
)
|
|
194
|
+
command: Optional[List[str]] = Field(
|
|
195
|
+
default=None,
|
|
196
|
+
description="""
|
|
197
|
+
Command to run as `subprocess.run(command)`.
|
|
198
|
+
Note, only either `function` or `command` can be provided.
|
|
199
|
+
""",
|
|
200
|
+
examples=[["python", "example.py", "--example", "example"]],
|
|
201
|
+
)
|
|
202
|
+
results: Optional[Dict[str, Any]] = Field(
|
|
203
|
+
default=None,
|
|
204
|
+
description="Results of the work performed.",
|
|
205
|
+
examples=[{"dm": 100.0, "snr": 10.0}],
|
|
206
|
+
)
|
|
207
|
+
products: Optional[List[str]] = Field(
|
|
208
|
+
default=None,
|
|
209
|
+
description="""
|
|
210
|
+
Name of the non-human-readable data products generated by the pipeline.
|
|
211
|
+
""",
|
|
212
|
+
examples=[["spectra.h5", "dm_vs_time.png"]],
|
|
213
|
+
)
|
|
214
|
+
plots: Optional[List[str]] = Field(
|
|
215
|
+
default=None,
|
|
216
|
+
validate_default=False,
|
|
217
|
+
description="""
|
|
218
|
+
Name of visual data products generated by the pipeline.
|
|
219
|
+
""",
|
|
220
|
+
examples=[["waterfall.png", "/arc/projects/chimefrb/9385707/9385707.png"]],
|
|
221
|
+
)
|
|
222
|
+
tags: Optional[List[str]] = Field(
|
|
223
|
+
default=None,
|
|
224
|
+
description="""
|
|
225
|
+
Searchable tags for the work. Merged with values from env WORKFLOW_TAGS.
|
|
226
|
+
""",
|
|
227
|
+
examples=[["tag", "tagged", "tagteam"]],
|
|
228
|
+
)
|
|
229
|
+
event: Optional[List[int]] = Field(
|
|
230
|
+
default=None,
|
|
231
|
+
description="Unique ID[s] the work was performed against.",
|
|
232
|
+
examples=[[9385707, 9385708]],
|
|
233
|
+
)
|
|
234
|
+
# * State Machine Attributes, set by the backend or optionally by the user.
|
|
235
|
+
# * These attributed describe the lifecycle of the work object, irrespective
|
|
236
|
+
# * of the current instantiation.
|
|
237
|
+
id: Optional[str] = Field(
|
|
238
|
+
default=None, description="Work ID created by the database."
|
|
239
|
+
)
|
|
240
|
+
creation: Optional[float] = Field(
|
|
241
|
+
default=None, description="Unix timestamp of when the work was created."
|
|
242
|
+
)
|
|
243
|
+
start: Optional[float] = Field(
|
|
244
|
+
default=None,
|
|
245
|
+
description="Unix timestamp when the work was started, reset at each attempt.",
|
|
246
|
+
)
|
|
247
|
+
stop: Optional[float] = Field(
|
|
248
|
+
default=None,
|
|
249
|
+
description="Unix timestamp when the work was stopped, reset at each attempt.",
|
|
250
|
+
)
|
|
251
|
+
attempt: int = Field(
|
|
252
|
+
default=0, ge=0, description="Attempt number at performing the work."
|
|
253
|
+
)
|
|
254
|
+
status: Literal["created", "queued", "running", "success", "failure"] = Field(
|
|
255
|
+
default="created", description="Status of the work."
|
|
256
|
+
)
|
|
257
|
+
timeout: int = Field(
|
|
258
|
+
default=3600,
|
|
259
|
+
ge=1,
|
|
260
|
+
le=86400,
|
|
261
|
+
description="""
|
|
262
|
+
Timeout in seconds for the work to finish.
|
|
263
|
+
After the timeout, the work is marked as failed and retried
|
|
264
|
+
if the number of attempts is less than the maximum number of retries.
|
|
265
|
+
Defaults 3600s (1 hr) with range of [1, 86400] (1s-24hrs).
|
|
266
|
+
""",
|
|
267
|
+
examples=[7200],
|
|
268
|
+
)
|
|
269
|
+
retries: int = Field(
|
|
270
|
+
default=2,
|
|
271
|
+
lt=6,
|
|
272
|
+
description="Number of retries before giving up. Defaults to 2.",
|
|
273
|
+
examples=[4],
|
|
274
|
+
)
|
|
275
|
+
priority: int = Field(
|
|
276
|
+
default=3,
|
|
277
|
+
ge=1,
|
|
278
|
+
le=5,
|
|
279
|
+
description="""
|
|
280
|
+
Priority of the work. Higher priority works are performed first.
|
|
281
|
+
i.e. 5 > 1 in priority. Defaults to 3.""",
|
|
282
|
+
examples=[1],
|
|
283
|
+
)
|
|
284
|
+
# Config defines the flow of state before and after the work.
|
|
285
|
+
config: Config = Field(
|
|
286
|
+
default=Config(),
|
|
287
|
+
description="Configuration of the work lifecycle.",
|
|
288
|
+
examples=[Config()],
|
|
289
|
+
)
|
|
290
|
+
# Notify defines the notification settings for the work.
|
|
291
|
+
notify: Notify = Field(
|
|
292
|
+
default=Notify(),
|
|
293
|
+
description="Notifications for work.",
|
|
294
|
+
examples=[Notify()],
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
###########################################################################
|
|
298
|
+
# Validation Methods for Work Attributes
|
|
299
|
+
###########################################################################
|
|
300
|
+
@field_validator("pipeline", mode="after", check_fields=True)
|
|
301
|
+
def validate_pipeline(cls, pipeline: str) -> str:
|
|
302
|
+
"""Validate the pipeline name.
|
|
303
|
+
|
|
304
|
+
Args:
|
|
305
|
+
pipeline (str): Name of the pipeline.
|
|
306
|
+
|
|
307
|
+
Raises:
|
|
308
|
+
ValueError: If the pipeline name contains any character that is not
|
|
309
|
+
|
|
310
|
+
Returns:
|
|
311
|
+
str: Validated pipeline name.
|
|
312
|
+
"""
|
|
313
|
+
for char in pipeline:
|
|
314
|
+
if not char.isalnum() and char not in ["-"]:
|
|
315
|
+
raise ValueError(
|
|
316
|
+
"pipeline name can only contain letters, numbers & hyphens."
|
|
317
|
+
)
|
|
318
|
+
return pipeline
|
|
319
|
+
|
|
320
|
+
@field_validator("creation")
|
|
321
|
+
def validate_creation(cls, creation: Optional[float]) -> float:
|
|
322
|
+
"""Validate and set the creation time.
|
|
323
|
+
|
|
324
|
+
Args:
|
|
325
|
+
creation (Optional[float]): Creation time in unix timestamp.
|
|
326
|
+
|
|
327
|
+
Returns:
|
|
328
|
+
float: Creation time in unix timestamp.
|
|
329
|
+
"""
|
|
330
|
+
if creation is None:
|
|
331
|
+
return time()
|
|
332
|
+
return creation
|
|
333
|
+
|
|
334
|
+
@model_validator(mode="before")
|
|
335
|
+
def pre_validation(cls, data: Any) -> Any:
|
|
336
|
+
"""Validate the work model before creating the object.
|
|
337
|
+
|
|
338
|
+
Args:
|
|
339
|
+
data (Any): Work data to validate.
|
|
340
|
+
|
|
341
|
+
Raises:
|
|
342
|
+
ValueError: If both `function` and `command` are set.
|
|
343
|
+
|
|
344
|
+
Returns:
|
|
345
|
+
Any: Validated work data.
|
|
346
|
+
"""
|
|
347
|
+
if data.get("function") and data.get("command"):
|
|
348
|
+
raise ValueError("Only either function or command can be provided.")
|
|
349
|
+
return data
|
|
350
|
+
|
|
351
|
+
@model_validator(mode="after")
|
|
352
|
+
def post_model_validation(self) -> "Work":
|
|
353
|
+
"""Validate the work model after creating the object.
|
|
354
|
+
|
|
355
|
+
Raises:
|
|
356
|
+
ValueError: Raised if,
|
|
357
|
+
the site provided is not allowed in the workspace.
|
|
358
|
+
|
|
359
|
+
Returns:
|
|
360
|
+
Work: The current work object.
|
|
361
|
+
"""
|
|
362
|
+
# Validate if the site provided is allowed in the workspace.
|
|
363
|
+
config: Dict[str, Any] = read.workspace(self.workspace)
|
|
364
|
+
sites: List[str] = config.get("sites", [])
|
|
365
|
+
if self.site not in sites:
|
|
366
|
+
error = (
|
|
367
|
+
f"site: {self.site} not in workspace: {self.workspace} sites: {sites}."
|
|
368
|
+
)
|
|
369
|
+
raise ValueError(error)
|
|
370
|
+
return self
|
|
371
|
+
|
|
372
|
+
###########################################################################
|
|
373
|
+
# Work Class Methods
|
|
374
|
+
###########################################################################
|
|
375
|
+
@property
|
|
376
|
+
def payload(self) -> Dict[str, Any]:
|
|
377
|
+
"""Return the dictionary representation of the work.
|
|
378
|
+
|
|
379
|
+
Returns:
|
|
380
|
+
Dict[str, Any]: The payload of the work.
|
|
381
|
+
Non-instanced attributes are excluded from the payload.
|
|
382
|
+
"""
|
|
383
|
+
payload: Dict[str, Any] = self.model_dump()
|
|
384
|
+
return payload
|
|
385
|
+
|
|
386
|
+
@classmethod
|
|
387
|
+
def from_json(cls, json: str) -> "Work":
|
|
388
|
+
"""Create a work from a json string.
|
|
389
|
+
|
|
390
|
+
Args:
|
|
391
|
+
json (str): The json string.
|
|
392
|
+
|
|
393
|
+
Returns:
|
|
394
|
+
Work: Work Object.
|
|
395
|
+
"""
|
|
396
|
+
return cls(**loads(json))
|
|
397
|
+
|
|
398
|
+
@classmethod
|
|
399
|
+
def from_dict(cls, payload: Dict[str, Any]) -> "Work":
|
|
400
|
+
"""Create a work from a dictionary.
|
|
401
|
+
|
|
402
|
+
Args:
|
|
403
|
+
payload (Dict[str, Any]): The dictionary.
|
|
404
|
+
|
|
405
|
+
Returns:
|
|
406
|
+
Work: Work Object.
|
|
407
|
+
"""
|
|
408
|
+
return cls(**payload)
|
|
409
|
+
|
|
410
|
+
###########################################################################
|
|
411
|
+
# HTTP Methods for the Work Class
|
|
412
|
+
###########################################################################
|
|
413
|
+
@classmethod
|
|
414
|
+
def withdraw(
|
|
415
|
+
cls,
|
|
416
|
+
pipeline: Union[str, List[str]],
|
|
417
|
+
event: Optional[List[int]] = None,
|
|
418
|
+
site: Optional[str] = None,
|
|
419
|
+
priority: Optional[int] = None,
|
|
420
|
+
user: Optional[str] = None,
|
|
421
|
+
tags: Optional[List[str]] = None,
|
|
422
|
+
parent: Optional[List[str]] = None,
|
|
423
|
+
timeout: float = 15.0,
|
|
424
|
+
token: Optional[SecretStr] = None,
|
|
425
|
+
http: Optional[HTTPContext] = None,
|
|
426
|
+
) -> Optional["Work"]:
|
|
427
|
+
"""Withdraw work from the buckets backend.
|
|
428
|
+
|
|
429
|
+
Args:
|
|
430
|
+
pipeline (Union[str, List[str]]): Name of the pipeline to withdraw work for.
|
|
431
|
+
event (Optional[List[int]]): Unique event ids to withdraw work for.
|
|
432
|
+
site (Optional[str]): Name of the site to withdraw work for.
|
|
433
|
+
priority (Optional[int]): Priority of the work to withdraw.
|
|
434
|
+
user (Optional[str]): Name of the user to withdraw work for.
|
|
435
|
+
tags (Optional[List[str]]): List of tags to withdraw work from.
|
|
436
|
+
parent (Optional[str]): Parent Pipeline ID of the work to withdraw.
|
|
437
|
+
timeout (float, optional): HTTP timeout in seconds. Defaults to 15.0.
|
|
438
|
+
token (Optional[SecretStr], optional): Workflow Access Token.
|
|
439
|
+
http (Optional[HTTPContext], optional): HTTP Context for connecting to
|
|
440
|
+
workflow servers.
|
|
441
|
+
|
|
442
|
+
Note:
|
|
443
|
+
`token` and `timeout` arguments can also be provided via the environment,
|
|
444
|
+
|
|
445
|
+
- "WORKFLOW_HTTP_TOKEN"
|
|
446
|
+
- "WORKFLOW_TOKEN"
|
|
447
|
+
- "GITHUB_TOKEN"
|
|
448
|
+
- "GITHUB_PAT"
|
|
449
|
+
- "WORKFLOW_HTTP_TIMEOUT"
|
|
450
|
+
|
|
451
|
+
The `http` argument can be provided, to avoid creating a new HTTPContext
|
|
452
|
+
object each time the work object interacts with a backend. This is useful
|
|
453
|
+
when doing bulk withdraws from the same backend.
|
|
454
|
+
|
|
455
|
+
Returns:
|
|
456
|
+
Optional[Work]: The withdrawn work if successful, None otherwise.
|
|
457
|
+
"""
|
|
458
|
+
# Context is used to source environtment variables, which are overwriten
|
|
459
|
+
# by the arguments passed to the function.
|
|
460
|
+
http = http or HTTPContext(timeout=timeout, token=token, backends=["buckets"])
|
|
461
|
+
payload = http.buckets.withdraw(
|
|
462
|
+
pipeline=pipeline,
|
|
463
|
+
event=event,
|
|
464
|
+
site=site,
|
|
465
|
+
priority=priority,
|
|
466
|
+
user=user,
|
|
467
|
+
tags=tags,
|
|
468
|
+
parent=parent,
|
|
469
|
+
)
|
|
470
|
+
if payload:
|
|
471
|
+
work = cls.from_dict(payload)
|
|
472
|
+
work.http = http
|
|
473
|
+
return work
|
|
474
|
+
return None
|
|
475
|
+
|
|
476
|
+
def deposit(
|
|
477
|
+
self,
|
|
478
|
+
return_ids: bool = False,
|
|
479
|
+
timeout: float = 15.0,
|
|
480
|
+
token: Optional[SecretStr] = None,
|
|
481
|
+
http: Optional[HTTPContext] = None,
|
|
482
|
+
) -> Union[bool, List[str]]:
|
|
483
|
+
"""Deposit work to the buckets backend.
|
|
484
|
+
|
|
485
|
+
Args:
|
|
486
|
+
return_ids (bool, optional): Return Database ID. Defaults to False.
|
|
487
|
+
timeout (float, optional): HTTP request timeout in seconds.
|
|
488
|
+
token (Optional[SecretStr], optional): Workflow Access Token.
|
|
489
|
+
http (Optional[HTTPContext], optional): HTTP Context for backend.
|
|
490
|
+
|
|
491
|
+
Note:
|
|
492
|
+
Both token and http can be either provided as arguments to the function
|
|
493
|
+
or also inherited from the work object itself.
|
|
494
|
+
|
|
495
|
+
Returns:
|
|
496
|
+
Union[bool, List[str]]: True if successful, False otherwise.
|
|
497
|
+
"""
|
|
498
|
+
self.token = token or self.token
|
|
499
|
+
self.http = (
|
|
500
|
+
http
|
|
501
|
+
or self.http
|
|
502
|
+
or HTTPContext(timeout=timeout, token=token, backends=["buckets"])
|
|
503
|
+
)
|
|
504
|
+
return self.http.buckets.deposit(works=[self.payload], return_ids=return_ids)
|
|
505
|
+
|
|
506
|
+
def update(self) -> bool:
|
|
507
|
+
"""Update work in the buckets backend.
|
|
508
|
+
|
|
509
|
+
Returns:
|
|
510
|
+
bool: True if successful, False otherwise.
|
|
511
|
+
"""
|
|
512
|
+
return self.http.buckets.update([self.payload])
|
|
513
|
+
|
|
514
|
+
def delete(self) -> bool:
|
|
515
|
+
"""Delete work from the buckets backend.
|
|
516
|
+
|
|
517
|
+
Returns:
|
|
518
|
+
bool: True if successful, False otherwise.
|
|
519
|
+
"""
|
|
520
|
+
return self.http.buckets.delete_ids([str(self.id)])
|