peak-sdk 1.0.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.
Files changed (51) hide show
  1. peak/__init__.py +36 -0
  2. peak/_version.py +21 -0
  3. peak/auth.py +22 -0
  4. peak/base_client.py +52 -0
  5. peak/cli/__init_.py +20 -0
  6. peak/cli/args.py +84 -0
  7. peak/cli/cli.py +56 -0
  8. peak/cli/helpers.py +187 -0
  9. peak/cli/press/__init__.py +21 -0
  10. peak/cli/press/apps/__init__.py +40 -0
  11. peak/cli/press/apps/deployments.py +238 -0
  12. peak/cli/press/apps/specs.py +387 -0
  13. peak/cli/press/blocks/__init__.py +40 -0
  14. peak/cli/press/blocks/deployments.py +240 -0
  15. peak/cli/press/blocks/specs.py +492 -0
  16. peak/cli/press/deployments.py +78 -0
  17. peak/cli/press/specs.py +131 -0
  18. peak/cli/resources/__init__.py +21 -0
  19. peak/cli/resources/artifacts.py +310 -0
  20. peak/cli/resources/images.py +886 -0
  21. peak/cli/resources/webapps.py +356 -0
  22. peak/cli/resources/workflows.py +703 -0
  23. peak/cli/ruff.toml +11 -0
  24. peak/cli/version.py +49 -0
  25. peak/compression.py +162 -0
  26. peak/config.py +24 -0
  27. peak/constants.py +105 -0
  28. peak/exceptions.py +217 -0
  29. peak/handler.py +358 -0
  30. peak/helpers.py +184 -0
  31. peak/logger.py +48 -0
  32. peak/press/__init__.py +28 -0
  33. peak/press/apps.py +669 -0
  34. peak/press/blocks.py +707 -0
  35. peak/press/deployments.py +145 -0
  36. peak/press/specs.py +260 -0
  37. peak/py.typed +0 -0
  38. peak/resources/__init__.py +28 -0
  39. peak/resources/artifacts.py +343 -0
  40. peak/resources/images.py +675 -0
  41. peak/resources/webapps.py +278 -0
  42. peak/resources/workflows.py +625 -0
  43. peak/session.py +259 -0
  44. peak/telemetry.py +201 -0
  45. peak/template.py +231 -0
  46. peak/validators.py +48 -0
  47. peak_sdk-1.0.0.dist-info/LICENSE +201 -0
  48. peak_sdk-1.0.0.dist-info/METADATA +199 -0
  49. peak_sdk-1.0.0.dist-info/RECORD +51 -0
  50. peak_sdk-1.0.0.dist-info/WHEEL +4 -0
  51. peak_sdk-1.0.0.dist-info/entry_points.txt +3 -0
@@ -0,0 +1,625 @@
1
+ #
2
+ # # Copyright © 2023 Peak AI Limited. or its affiliates. All Rights Reserved.
3
+ # #
4
+ # # Licensed under the Apache License, Version 2.0 (the "License"). You
5
+ # # may not use this file except in compliance with the License. A copy of
6
+ # # the License is located at:
7
+ # #
8
+ # # https://github.com/PeakBI/peak-sdk/blob/main/LICENSE
9
+ # #
10
+ # # or in the "license" file accompanying this file. This file is
11
+ # # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
12
+ # # ANY KIND, either express or implied. See the License for the specific
13
+ # # language governing permissions and limitations under the License.
14
+ # #
15
+ # # This file is part of the peak-sdk.
16
+ # # see (https://github.com/PeakBI/peak-sdk)
17
+ # #
18
+ # # You should have received a copy of the APACHE LICENSE, VERSION 2.0
19
+ # # along with this program. If not, see <https://apache.org/licenses/LICENSE-2.0>
20
+ #
21
+ """Workflow client module."""
22
+ from __future__ import annotations
23
+
24
+ from typing import Any, Dict, Iterator, List, Literal, Optional, overload
25
+
26
+ from peak.base_client import BaseClient
27
+ from peak.constants import ContentType, HttpMethods
28
+ from peak.exceptions import InvalidParameterException
29
+ from peak.helpers import (
30
+ combine_dictionaries,
31
+ map_user_options,
32
+ variables_to_dict,
33
+ )
34
+ from peak.session import Session
35
+
36
+
37
+ class Workflow(BaseClient):
38
+ """Client class for interacting with workflows resource."""
39
+
40
+ BASE_ENDPOINT = "workflows/api/v1"
41
+
42
+ @overload
43
+ def list_workflows(
44
+ self: Workflow,
45
+ workflow_status: Optional[List[str]] = None,
46
+ last_execution_status: Optional[List[str]] = None,
47
+ last_modified_by: Optional[List[str]] = None,
48
+ page_size: Optional[int] = None,
49
+ page_number: Optional[int] = None,
50
+ name: Optional[str] = None,
51
+ *,
52
+ return_iterator: Literal[False],
53
+ ) -> Dict[str, Any]:
54
+ ...
55
+
56
+ @overload
57
+ def list_workflows(
58
+ self: Workflow,
59
+ workflow_status: Optional[List[str]] = None,
60
+ last_execution_status: Optional[List[str]] = None,
61
+ last_modified_by: Optional[List[str]] = None,
62
+ page_size: Optional[int] = None,
63
+ page_number: Optional[int] = None,
64
+ name: Optional[str] = None,
65
+ *,
66
+ return_iterator: Literal[True] = True,
67
+ ) -> Iterator[Dict[str, Any]]:
68
+ ...
69
+
70
+ def list_workflows(
71
+ self: Workflow,
72
+ workflow_status: Optional[List[str]] = None,
73
+ last_execution_status: Optional[List[str]] = None,
74
+ last_modified_by: Optional[List[str]] = None,
75
+ page_size: Optional[int] = None,
76
+ page_number: Optional[int] = None,
77
+ name: Optional[str] = None,
78
+ *,
79
+ return_iterator: bool = True,
80
+ ) -> Iterator[Dict[str, Any]] | Dict[str, Any]:
81
+ """Retrieve the list of workflows.
82
+
83
+ REFERENCE:
84
+ 🔗 `API Documentation <https://service.peak.ai/workflows/api-docs/index.htm#/Workflows/get-workflows>`__
85
+
86
+ Args:
87
+ workflow_status (List[str] | None): List of status to filter workflow. Default is None.
88
+ last_execution_status (str | None): The last execution status of the workflow. Default is None.
89
+ last_modified_by (str | None): The user who last modified the workflow. Default is None.
90
+ page_size (int | None): The number of workflows per page.
91
+ page_number (int | None): The page number to retrieve. Only used when return_iterator is False.
92
+ name (str | None): Search workflows by name.
93
+ return_iterator (bool): Whether to return an iterator object or list of workflows for a specified page number, defaults to True.
94
+
95
+ Returns:
96
+ Iterator[Dict[str, Any]] | Dict[str, Any]: An iterator object which returns an element per iteration, until there are no more elements to return.
97
+ If `return_iterator` is set to False, a dictionary containing the list and pagination details is returned instead.
98
+
99
+ Set `return_iterator` to True if you want automatic client-side pagination, or False if you want server-side pagination.
100
+
101
+ Raises:
102
+ BadRequestException: The given request parameters are invalid.
103
+ UnauthorizedException: The credentials are invalid.
104
+ ForbiddenException: The user does not have permission to perform the operation.
105
+ InternalServerErrorException: The server failed to process the request.
106
+ StopIteration: There are no more pages to list
107
+ """
108
+ method, endpoint = HttpMethods.GET, f"{self.BASE_ENDPOINT}/workflows/"
109
+ params: Dict[str, Any] = {
110
+ "pageSize": page_size,
111
+ "workflowStatus": workflow_status,
112
+ "lastExecutionStatus": last_execution_status,
113
+ "lastModifiedBy": last_modified_by,
114
+ "searchTerm": name,
115
+ }
116
+
117
+ if return_iterator:
118
+ return self.session.create_generator_request(
119
+ endpoint,
120
+ method,
121
+ content_type=ContentType.APPLICATION_JSON,
122
+ response_key="workflows",
123
+ params=params,
124
+ )
125
+
126
+ return self.session.create_request( # type: ignore[no-any-return]
127
+ endpoint,
128
+ method,
129
+ content_type=ContentType.APPLICATION_JSON,
130
+ params={**params, "pageNumber": page_number},
131
+ )
132
+
133
+ def create_workflow(self: Workflow, body: Dict[str, Any]) -> Dict[str, int]:
134
+ """Create a new workflow. Workflows with only standard steps are supported.
135
+
136
+ REFERENCE:
137
+ 🔗 `API Documentation <https://service.peak.ai/workflows/api-docs/index.htm#/Workflows/create-workflow>`__
138
+
139
+ Args:
140
+ body (Dict[str, Any]): A dictionary containing the workflow config.
141
+
142
+ Returns:
143
+ Dict[str, int]: Id of the newly created workflow.
144
+
145
+ Raises:
146
+ BadRequestException: The given request parameters are invalid.
147
+ UnauthorizedException: The credentials are invalid.
148
+ ForbiddenException: The user does not have permission to perform the operation.
149
+ InternalServerErrorException: The server failed to process the request.
150
+ """
151
+ method, endpoint = HttpMethods.POST, f"{self.BASE_ENDPOINT}/workflows/"
152
+
153
+ return self.session.create_request( # type: ignore[no-any-return]
154
+ endpoint,
155
+ method,
156
+ content_type=ContentType.APPLICATION_JSON,
157
+ body=body,
158
+ )
159
+
160
+ def create_or_update_workflow(self: Workflow, body: Dict[str, Any]) -> Dict[str, int]:
161
+ """Creates a new workflow or updates an existing workflow based on workflow name.
162
+
163
+ REFERENCE:
164
+ 🔗 `API Documentation <https://service.peak.ai/workflows/api-docs/index.htm#/Workflows/create-workflow>`__
165
+
166
+ Args:
167
+ body (Dict[str, Any]): A dictionary containing the workflow config.
168
+
169
+ Returns:
170
+ Dict[str, int]: Id of the newly created or updated workflow.
171
+
172
+ Raises:
173
+ BadRequestException: The given request parameters are invalid.
174
+ UnauthorizedException: The credentials are invalid.
175
+ ForbiddenException: The user does not have permission to perform the operation.
176
+ InternalServerErrorException: The server failed to process the request.
177
+ """
178
+ workflow_name = body["name"] if "name" in body else ""
179
+ response = (
180
+ {}
181
+ if not len(workflow_name)
182
+ else self.list_workflows(page_size=100, return_iterator=False, name=workflow_name)
183
+ )
184
+ filtered_workflows = list(
185
+ filter(lambda workflow: workflow.get("name", "") == workflow_name, response.get("workflows", [])),
186
+ )
187
+
188
+ if len(filtered_workflows) > 0:
189
+ workflow_id = filtered_workflows[0]["id"]
190
+ return self.update_workflow(workflow_id=workflow_id, body=body)
191
+
192
+ return self.create_workflow(body=body)
193
+
194
+ def describe_workflow(
195
+ self: Workflow,
196
+ workflow_id: int,
197
+ ) -> Dict[str, Any]:
198
+ """Retrieve details of a specific workflow. Workflows with only standard steps can be described.
199
+
200
+ REFERENCE:
201
+ 🔗 `API Documentation <https://service.peak.ai/workflows/api-docs/index.htm#/Workflows/describe-workflow>`__
202
+
203
+ Args:
204
+ workflow_id (int): The ID of the workflow to retrieve.
205
+
206
+ Returns:
207
+ Dict[str, Any]: A dictionary containing the details of the workflow.
208
+
209
+ Raises:
210
+ BadRequestException: The given request parameters are invalid.
211
+ UnauthorizedException: The credentials are invalid.
212
+ ForbiddenException: The user does not have permission to perform the operation.
213
+ NotFoundException: The given workflow does not exist.
214
+ UnprocessableEntityException: The server was unable to process the request.
215
+ InternalServerErrorException: The server failed to process the request.
216
+ """
217
+ method, endpoint = HttpMethods.GET, f"{self.BASE_ENDPOINT}/workflows/{workflow_id}"
218
+
219
+ return self.session.create_request( # type: ignore[no-any-return]
220
+ endpoint,
221
+ method,
222
+ content_type=ContentType.APPLICATION_JSON,
223
+ )
224
+
225
+ def update_workflow(self: Workflow, workflow_id: int, body: Dict[str, Any]) -> Dict[str, Any]:
226
+ """Update an existing workflow. Workflows with only standard steps are supported.
227
+
228
+ REFERENCE:
229
+ 🔗 `API Documentation <https://service.peak.ai/workflows/api-docs/index.htm#/Workflows/update-workflow>`__
230
+
231
+ Args:
232
+ workflow_id (int): The ID of the workflow to update.
233
+ body (dict): A dictionary containing the updated workflow details.
234
+
235
+ Returns:
236
+ Dict[str, int]: Id of the updated workflow.
237
+
238
+ Raises:
239
+ BadRequestException: The given request parameters are invalid.
240
+ UnauthorizedException: The credentials are invalid.
241
+ ForbiddenException: The user does not have permission to perform the operation.
242
+ NotFoundException: The given workflow does not exist.
243
+ ConflictException: The workflow is in a conflicting state while deleting.
244
+ InternalServerErrorException: The server failed to process the request.
245
+ """
246
+ method, endpoint = HttpMethods.PUT, f"{self.BASE_ENDPOINT}/workflows/{workflow_id}"
247
+ return self.session.create_request( # type: ignore[no-any-return]
248
+ endpoint,
249
+ method,
250
+ content_type=ContentType.APPLICATION_JSON,
251
+ body=body,
252
+ )
253
+
254
+ def patch_workflow( # noqa: C901, PLR0912
255
+ self: Workflow,
256
+ workflow_id: int,
257
+ body: Optional[Dict[str, Any]] = None,
258
+ name: Optional[str] = None,
259
+ repository: Optional[str] = None,
260
+ branch: Optional[str] = None,
261
+ token: Optional[str] = None,
262
+ command: Optional[str] = None,
263
+ image_id: Optional[int] = None,
264
+ image_version_id: Optional[int] = None,
265
+ instance_type_id: Optional[int] = None,
266
+ storage: Optional[str] = None,
267
+ step_timeout: Optional[int] = None,
268
+ clear_image_cache: Optional[bool] = None,
269
+ step_names: Optional[List[str]] = None,
270
+ ) -> Dict[str, Any]:
271
+ """Update an existing workflow. Workflows with only standard steps are supported.
272
+
273
+ - This function allows to efficiently modify trigger details, watchers, workflow name, and specific step attributes such as repository URL, branch, token, image ID, version ID etc.
274
+
275
+ - By specifying `step_names`, we can globally update specified steps with provided parameters, streamlining the update process. If `step_names` is not provided, all the steps for that workflow would be updated.
276
+
277
+ - Alternatively, we can utilize the **body** parameter to selectively modify individual step attributes across different steps. With this, we can also add new steps to the workflow by providing the parameters required by the step.
278
+
279
+ - If both body and specific parameters are used, the latter takes precedence.
280
+
281
+ Args:
282
+ workflow_id (int): The ID of the workflow to patch.
283
+ body (Dict[str, Any] | None): A dictionary containing the updated workflow details.
284
+ name (str | None): The name of the workflow.
285
+ repository (str | None): URL of the repository containing the required files.
286
+ branch (str | None): The branch of the repository to use.
287
+ token (str | None): The token to be used to access the repository.
288
+ command (str | None): The command to run when workflow step is executed.
289
+ image_id (int | None): The ID of the image to use for the workflow step.
290
+ image_version_id (int | None): The ID of the image version to use for the workflow step.
291
+ instance_type_id (int | None): The ID of the instance type to use for the workflow step.
292
+ storage (str | None): The storage to use for the workflow step in GB. For example, "10GB".
293
+ step_timeout (int | None): Time after which the step timeouts.
294
+ clear_image_cache (boolean | None): Whether to clear image cache on workflow execution.
295
+ step_names (List[str] | None): The workflow steps to update. If not provided, all steps will be updated.
296
+
297
+ Returns:
298
+ Dict[str, Any]: A dictionary containing the workflow ID.
299
+
300
+ Raises:
301
+ InvalidParameterException: The given request parameters are invalid.
302
+ UnauthorizedException: The credentials are invalid.
303
+ ForbiddenException: The user does not have permission to perform the operation.
304
+ NotFoundException: The given workflow does not exist.
305
+ ConflictException: The workflow is in a conflicting state while deleting.
306
+ InternalServerErrorException: The server failed to process the request.
307
+ """
308
+ user_options = variables_to_dict(
309
+ name,
310
+ repository,
311
+ branch,
312
+ token,
313
+ command,
314
+ image_id,
315
+ image_version_id,
316
+ instance_type_id,
317
+ storage,
318
+ step_timeout,
319
+ clear_image_cache,
320
+ )
321
+
322
+ if not user_options and not body:
323
+ raise InvalidParameterException(
324
+ message="Request body or at least one parameter must be provided to update the workflow.",
325
+ )
326
+
327
+ workflow_details = self.describe_workflow(workflow_id=workflow_id)
328
+
329
+ for step_name in step_names or []:
330
+ if step_name not in workflow_details["steps"]:
331
+ raise InvalidParameterException(
332
+ message=f"Step name {step_name} does not exist for workflow {workflow_id}",
333
+ )
334
+
335
+ # First, we modify steps in workflow details to the expected format for the API
336
+
337
+ step_keys_to_skip = ["imageName", "imageVersion"]
338
+
339
+ updated_workflow_details: Dict[str, Any] = {
340
+ "name": workflow_details["name"],
341
+ "tags": workflow_details["tags"],
342
+ "watchers": workflow_details["watchers"],
343
+ "triggers": [],
344
+ "steps": {},
345
+ }
346
+
347
+ if workflow_details.get("triggers"):
348
+ triggers = workflow_details["triggers"]
349
+ if triggers[0].get("cron"):
350
+ updated_workflow_details["triggers"] = [{"cron": triggers[0]["cron"]}]
351
+ elif triggers[0].get("webhook"):
352
+ updated_workflow_details["triggers"] = [{"webhook": True, "webhookPolicy": "preserve"}]
353
+
354
+ for step_name, step in workflow_details["steps"].items():
355
+ updated_workflow_details["steps"][step_name] = {}
356
+ for key, value in step.items():
357
+ if key not in step_keys_to_skip and value is not None:
358
+ updated_workflow_details["steps"][step_name][key] = value
359
+ if key == "repository" and not value.get("token", {}):
360
+ updated_workflow_details["steps"][step_name]["repository"].pop("token", None)
361
+ if key == "parameters" and "env" in value: ## Describe workflow returns env as a list of dictionaries
362
+ env = {}
363
+ for env_dict in value["env"]:
364
+ env.update(env_dict)
365
+ updated_workflow_details["steps"][step_name]["parameters"]["env"] = env
366
+
367
+ ## Second, we merge updated_workflow_details with the user provided body
368
+
369
+ updated_body: Dict[str, Any] = updated_workflow_details.copy()
370
+
371
+ if body:
372
+ for key, value in body.items():
373
+ if key == "steps":
374
+ for step_name, step in body["steps"].items():
375
+ updated_body["steps"][step_name] = combine_dictionaries(
376
+ updated_body["steps"].get(step_name, {}),
377
+ step,
378
+ nested_keys_to_skip=["env"],
379
+ )
380
+ else:
381
+ updated_body[key] = value
382
+
383
+ ## Finally, we update the body with the user provided parameters
384
+
385
+ if user_options.get("repository"):
386
+ user_options["url"] = user_options["repository"]
387
+ del user_options["repository"]
388
+
389
+ keys_mapping: Dict[str, str] = {
390
+ "url": "repository",
391
+ "branch": "repository",
392
+ "token": "repository",
393
+ "instanceTypeId": "resources",
394
+ "storage": "resources",
395
+ }
396
+
397
+ user_options = map_user_options(user_options, keys_mapping)
398
+
399
+ if user_options:
400
+ if user_options.get("name"):
401
+ updated_body["name"] = user_options["name"]
402
+ del user_options["name"]
403
+ for step_name in updated_body["steps"]:
404
+ if not step_names or step_name in step_names:
405
+ updated_body["steps"][step_name] = combine_dictionaries(
406
+ updated_body["steps"].get(step_name, {}),
407
+ user_options,
408
+ )
409
+
410
+ return self.update_workflow(workflow_id=workflow_id, body=updated_body)
411
+
412
+ def delete_workflow(
413
+ self: Workflow,
414
+ workflow_id: int,
415
+ ) -> Dict[None, None]:
416
+ """Delete a workflow.
417
+
418
+ REFERENCE:
419
+ 🔗 `API Documentation <https://service.peak.ai/workflows/api-docs/index.htm#/Workflows/delete-workflow>`__
420
+
421
+ Args:
422
+ workflow_id (int): The ID of the workflow to delete.
423
+
424
+ Returns:
425
+ dict: Empty dictionary object.
426
+
427
+ Raises:
428
+ UnauthorizedException: The credentials are invalid.
429
+ ForbiddenException: The user does not have permission to perform the operation.
430
+ NotFoundException: The given workflow does not exist.
431
+ ConflictException: If the workflow is in a conflicting state while deleting.
432
+ InternalServerErrorException: The server failed to process the request.
433
+ """
434
+ method, endpoint = HttpMethods.DELETE, f"{self.BASE_ENDPOINT}/workflows/{workflow_id}"
435
+
436
+ return self.session.create_request( # type: ignore[no-any-return]
437
+ endpoint,
438
+ method,
439
+ content_type=ContentType.APPLICATION_JSON,
440
+ )
441
+
442
+ def execute_workflow(
443
+ self: Workflow,
444
+ workflow_id: int,
445
+ body: Optional[Dict[str, Any]] = None,
446
+ ) -> Dict[str, str]:
447
+ """Start a workflow run.
448
+
449
+ REFERENCE:
450
+ 🔗 `API Documentation <https://service.peak.ai/workflows/api-docs/index.htm#/Workflows/execute-workflow>`__
451
+
452
+ Args:
453
+ workflow_id (int): ID of the workflow to delete.
454
+ body: (Dict[str, Any]): The parameters to be passed while running the workflow. More details can be found in the API doc - https://service.peak.ai/workflows/api-docs/index.htm#/Workflows/execute-workflow
455
+
456
+ Returns:
457
+ Dict[str, str]: Execution ID of the run.
458
+
459
+ Raises:
460
+ UnauthorizedException: The credentials are invalid.
461
+ ForbiddenException: The user does not have permission to perform the operation.
462
+ NotFoundException: The given workflow does not exist.
463
+ ConflictException: The workflow is in a conflicting state and new run cannot be started.
464
+ InternalServerErrorException: The server failed to process the request.
465
+ """
466
+ method, endpoint = HttpMethods.POST, f"{self.BASE_ENDPOINT}/workflows/{workflow_id}/execute"
467
+
468
+ return self.session.create_request( # type: ignore[no-any-return]
469
+ endpoint,
470
+ method,
471
+ content_type=ContentType.APPLICATION_JSON,
472
+ body=body,
473
+ )
474
+
475
+ def list_resources(
476
+ self: Workflow,
477
+ ) -> List[Dict[str, Any]]:
478
+ """Lists all available resources for the workflows.
479
+
480
+ REFERENCE:
481
+ 🔗 `API Documentation <https://service.peak.ai/workflows/api-docs/index.htm#/Resources/get-resources>`__
482
+
483
+ Returns:
484
+ Dict[str, Any]: A dictionary containing the list of available resources.
485
+
486
+ Raises:
487
+ UnauthorizedException: The credentials are invalid.
488
+ ForbiddenException: The user does not have permission to perform the operation.
489
+ NotFoundException: The given workflow does not exist.
490
+ ConflictException: The workflow is in a conflicting state and new run cannot be started.
491
+ InternalServerErrorException: The server failed to process the request.
492
+ """
493
+ method, endpoint = HttpMethods.GET, f"{self.BASE_ENDPOINT}/resources"
494
+
495
+ return self.session.create_request( # type: ignore[no-any-return]
496
+ endpoint,
497
+ method,
498
+ content_type=ContentType.APPLICATION_JSON,
499
+ )
500
+
501
+ def get_default_resource(
502
+ self: Workflow,
503
+ ) -> Dict[str, Any]:
504
+ """Default resource values that will be used in case `resource` key is not provided for the workflows.
505
+
506
+ REFERENCE:
507
+ 🔗 `API Documentation <https://service.peak.ai/workflows/api-docs/index.htm#/Resources/get-default-resources>`__
508
+
509
+ Returns:
510
+ Dict[str, Any]: Default resource values
511
+
512
+ Raises:
513
+ UnauthorizedException: The credentials are invalid.
514
+ ForbiddenException: The user does not have permission to perform the operation.
515
+ InternalServerErrorException: The server failed to process the request.
516
+ """
517
+ method, endpoint = HttpMethods.GET, f"{self.BASE_ENDPOINT}/resources/defaults"
518
+
519
+ return self.session.create_request( # type: ignore[no-any-return]
520
+ endpoint,
521
+ method,
522
+ content_type=ContentType.APPLICATION_JSON,
523
+ )
524
+
525
+ @overload
526
+ def list_executions(
527
+ self: Workflow,
528
+ workflow_id: int,
529
+ date_from: Optional[str] = None,
530
+ date_to: Optional[str] = None,
531
+ page_size: Optional[int] = None,
532
+ page_number: Optional[int] = None,
533
+ *,
534
+ return_iterator: Literal[False],
535
+ ) -> Dict[str, Any]:
536
+ ...
537
+
538
+ @overload
539
+ def list_executions(
540
+ self: Workflow,
541
+ workflow_id: int,
542
+ date_from: Optional[str] = None,
543
+ date_to: Optional[str] = None,
544
+ page_size: Optional[int] = None,
545
+ page_number: Optional[int] = None,
546
+ *,
547
+ return_iterator: Literal[True] = True,
548
+ ) -> Iterator[Dict[str, Any]]:
549
+ ...
550
+
551
+ def list_executions(
552
+ self: Workflow,
553
+ workflow_id: int,
554
+ date_from: Optional[str] = None,
555
+ date_to: Optional[str] = None,
556
+ page_size: Optional[int] = None,
557
+ page_number: Optional[int] = None,
558
+ *,
559
+ return_iterator: bool = True,
560
+ ) -> Iterator[Dict[str, Any]] | Dict[str, Any]:
561
+ """Lists executions for the given workflow.
562
+
563
+ REFERENCE:
564
+ 🔗 `API Documentation <https://service.peak.ai/workflows/api-docs/index.htm#/Executions/get-workflow-executions>`__
565
+
566
+ Args:
567
+ workflow_id (int): ID of the workflow to fetch executions.
568
+ date_from (str | None): The date after which the executions should be included (in ISO format). Defaults to None
569
+ date_to (str | None): The date till which the executions should be included (in ISO format). Defaults to None
570
+ page_size (int | None): Number of executions per page.
571
+ page_number (int | None): Page number to fetch. Only used when return_iterator is False.
572
+ return_iterator (bool): Whether to return an iterator object or list of executions for a specified page number, defaults to True.
573
+
574
+ Returns:
575
+ Iterator[Dict[str, Any]] | Dict[str, Any]: An iterator object which returns an element per iteration, until there are no more elements to return.
576
+ If `return_iterator` is set to False, a dictionary containing the list and pagination details is returned instead.
577
+
578
+ Set `return_iterator` to True if you want automatic client-side pagination, or False if you want server-side pagination.
579
+
580
+ Raises:
581
+ BadRequestException: BadRequestException: The given request parameters are invalid.
582
+ UnauthorizedException: The credentials are invalid.
583
+ ForbiddenException: The user does not have permission to perform the operation.
584
+ NotFoundException: The given workflow does not exist.
585
+ InternalServerErrorException: The server failed to process the request.
586
+ StopIteration: There are no more pages to list
587
+ """
588
+ method, endpoint = HttpMethods.GET, f"{self.BASE_ENDPOINT}/workflows/executions/{workflow_id}"
589
+
590
+ params: Dict[str, Any] = {
591
+ "dateTo": date_to,
592
+ "dateFrom": date_from,
593
+ "pageSize": page_size,
594
+ }
595
+
596
+ if return_iterator:
597
+ return self.session.create_generator_request(
598
+ endpoint,
599
+ method,
600
+ content_type=ContentType.APPLICATION_JSON,
601
+ response_key="executions",
602
+ params=params,
603
+ )
604
+
605
+ return self.session.create_request( # type: ignore[no-any-return]
606
+ endpoint,
607
+ method,
608
+ content_type=ContentType.APPLICATION_JSON,
609
+ params={**params, "pageNumber": page_number},
610
+ )
611
+
612
+
613
+ def get_client(session: Optional[Session] = None) -> Workflow:
614
+ """Returns a Workflow client, If no session is provided, a default session is used.
615
+
616
+ Args:
617
+ session (Optional[Session]): A Session Object. Default is None.
618
+
619
+ Returns:
620
+ Workflow: the workflow client object
621
+ """
622
+ return Workflow(session)
623
+
624
+
625
+ __all__: List[str] = ["get_client"]