forked from OpenJobDescription/openjd-model-for-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_model.py
More file actions
4226 lines (3596 loc) · 172 KB
/
Copy path_model.py
File metadata and controls
4226 lines (3596 loc) · 172 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
from __future__ import annotations
import re
import secrets
import string
from decimal import Decimal, InvalidOperation
from enum import Enum
from graphlib import CycleError, TopologicalSorter
from typing import Any, ClassVar, Literal, Optional, Type, Union, cast, Iterable
from typing_extensions import Annotated, Self
from pydantic import (
field_validator,
model_validator,
ConfigDict,
Discriminator,
StringConstraints,
Field,
PositiveInt,
PositiveFloat,
StrictBool,
StrictInt,
Tag,
ValidationError,
ValidationInfo,
)
from pydantic_core import InitErrorDetails
from pydantic.fields import ModelPrivateAttr
from .._format_strings import FormatString
from .._errors import ExpressionError, TokenError
from .._capabilities import (
validate_amount_capability_name,
validate_attribute_capability_name,
)
from .._internal import (
CombinationExpressionParser,
validate_step_parameter_space_dimensions,
validate_step_parameter_space_chunk_constraint,
validate_unique_elements,
validate_int_fmtstring_field,
validate_float_fmtstring_field,
validate_list_field,
)
from .._internal._variable_reference_validation import (
prevalidate_model_template_variable_references,
)
from .._range_expr import IntRangeExpr
from .._types import (
DefinesTemplateVariables,
JobCreateAsMetadata,
JobCreationMetadata,
JobParameterInterface,
ModelParsingContextInterface,
OpenJDModel,
ResolutionScope,
SpecificationRevision,
TemplateSpecificationVersion,
TemplateVariableDef,
)
# Error message constants
_ALLOWED_VALUES_NONE_ERROR = "allowedValues cannot be None. The field must contain at least one value or be omitted entirely."
_VALUE_LESS_THAN_MIN_ERROR = "Value less than minValue."
_VALUE_LARGER_THAN_MAX_ERROR = "Value larger than maxValue."
# Interpreter syntax sugar configuration: (command, extension, arg_prefix)
_INTERPRETER_MAP: dict[str, tuple[str, str, list[str]]] = {
"python": ("python", ".py", []),
"bash": ("bash", ".sh", []),
"cmd": ("cmd", ".bat", ["/C"]),
"powershell": ("powershell", ".ps1", ["-File"]),
"node": ("node", ".js", []),
}
class ModelParsingContext(ModelParsingContextInterface):
"""Context required while parsing an OpenJDModel. An instance of this class
must be provided when calling model_validate.
OpenJDModelSubclass.model_validate(data, context=ModelParsingContext())
Individual validators receive this value as ValidationInfo.context.
"""
def __init__(self, *, supported_extensions: Optional[Iterable[str]] = None) -> None:
super().__init__(
spec_rev=SpecificationRevision.v2023_09, supported_extensions=supported_extensions
)
class OpenJDModel_v2023_09(OpenJDModel): # noqa: N801
revision = SpecificationRevision.v2023_09
model_parsing_context_type = ModelParsingContext
@staticmethod
def supported_extension_names() -> set[str]:
"""Returns the list of all extension names supported by the 2023-09 specification version."""
return {v.value for v in ExtensionName}
class ExtensionName(str, Enum):
"""Enumeration of all extensions supported for the 2023-09 specification revision.
This appears in the 'extensions' list property of all model instances.
"""
# https://github.com/OpenJobDescription/openjd-specifications/blob/mainline/rfcs/0001-task-chunking.md
TASK_CHUNKING = "TASK_CHUNKING"
# Extension that enables the use of openjd_redacted_env for setting environment variables with redacted values in logs
REDACTED_ENV_VARS = "REDACTED_ENV_VARS"
# Extension for increased limits, format strings in timeout/min/max/notifyPeriodInSeconds,
# endOfLine control, and script interpreter syntax sugar
FEATURE_BUNDLE_1 = "FEATURE_BUNDLE_1"
# Expression Language (RFCs 0005/0006/0007): rich {{ }} expressions, function
# library, and extended job-parameter types. Evaluated by the Rust openjd-expr
# engine via the openjd._openjd_rs bindings.
EXPR = "EXPR"
# Environment Wrap Actions (RFC 0008): onWrapEnvEnter/onWrapTaskRun/onWrapEnvExit
# on <EnvironmentActions>. Requires EXPR.
WRAP_ACTIONS = "WRAP_ACTIONS"
ExtensionNameList = Annotated[list[str], Field(min_length=1)]
class ValueReferenceConstants(Enum):
"""Prefixes used when referencing values in format strings."""
JOB_PARAMETER_PREFIX = "Param"
"""Prefix for referencing processed Job Parameters.
"""
JOB_PARAMETER_RAWPREFIX = "RawParam"
"""Prefix for referencing Job Parameters' input value.
"""
ENV_FILE_PREFIX = "Env.File"
"""Prefix for referencing an Environment's embedded files.
"""
TASK_FILE_PREFIX = "Task.File"
"""Prefix for referencing an embedded file that is defined within
a Step Script.
"""
TASK_PARAMETER_PREFIX = "Task.Param"
"""Prefix for referencing a processed Task Parameter's value.
"""
TASK_PARAMETER_RAWPREFIX = "Task.RawParam"
"""Prefix for referencing Task Parameter's input value.
"""
WORKING_DIRECTORY = "Session.WorkingDirectory"
"""The reference to the Session Working Directory.
This will resolve to the fully qualified temporary directory on disk
that is being used as the working directory for the Session.
"""
HAS_PATH_MAPPING_RULES = "Session.HasPathMappingRules"
"""The reference to whether or not a Task/Environment run
has path mapping rules available.
Value of this value will be either: "true" or "false"
( case sensitive )
"""
PATH_MAPPING_RULES_FILE = "Session.PathMappingRulesFile"
"""A value that resolves to the fully qualified file location
of a JSON file that contains the path mapping rules. This file will
be in the Session's Working Directory.
If there are no path mapping rules, then this file will contain
only: {}
"""
# ==================================================================
# ============================= String types =======================
# ==================================================================
# All unicode characters except for those in the Cc unicode character
# category.
# Cc category =
# C0 = 0x00-0x1F
# https://www.unicode.org/charts/PDF/U0000.pdf
# DEL character (0x7F)
# C1 = 0x80-0x9F
# https://www.unicode.org/charts/PDF/U0080.pdf
_Cc_characters = r"\u0000-\u001F\u007F-\u009F"
_standard_string_regex = rf"(?-m:^[^{_Cc_characters}]+\z)"
# Latin alphanumeric, starting with a letter
_identifier_regex = r"(?-m:^[A-Za-z_][A-Za-z0-9_]*\z)"
# Regex for defining file filter patterns allowed for use in file dialogs.
# 1. Allowable values: "*", "*.*", and "*.[:file-extension-chars:]+".
# The characters that :file-extension-chars: can take on are any unicode character except:
# a. The Cc unicode character category.
# b. Path separators "\" and "/".
# c. Wildcard characters "*", "?", "[", "]".
# d. Characters commonly disallowed in paths "#", "%", "&", "{", "}", "<", ">",
# "$", "!", "'", "\"", ":", "@", "`", "|", "=".
_file_dialog_filter_pattern_regex = (
rf"(?-m:^(?:\*|\*\.\*|\*\."
rf"[^{_Cc_characters}\\/\*"
rf"\?\[\]#%&\{{\}}<>\$\!'"
rf"\\\":@`|=]+)\z)"
)
class JobTemplateName(FormatString):
_min_length = 1
# Max length is validated after resolution in Job model, not here
# because the template name can contain format strings
# All unicode except the [Cc] (control characters) category
_regex = f"(?-m:^[^{_Cc_characters}]+\\Z)"
def __new__(cls, value: str, *, context: ModelParsingContextInterface = ModelParsingContext()):
return super().__new__(cls, value, context=context)
JobName = Annotated[
str,
StringConstraints(min_length=1, max_length=512, strict=True, pattern=_standard_string_regex),
]
Identifier = Annotated[
str, StringConstraints(min_length=1, max_length=512, strict=True, pattern=_identifier_regex)
]
Description = Annotated[
str,
StringConstraints(
min_length=1,
max_length=2048,
strict=True,
# All unicode except the [Cc] (control characters) category
# Allow CR, LF, and TAB.
pattern=f"(?-m:^(?:[^{_Cc_characters}]|[\r\n\t])+\\z)",
),
]
EnvironmentName = Annotated[
str,
StringConstraints(min_length=1, max_length=512, strict=True, pattern=_standard_string_regex),
]
StepName = Annotated[
str,
StringConstraints(min_length=1, max_length=512, strict=True, pattern=_standard_string_regex),
]
ParameterStringValue = Annotated[str, StringConstraints(min_length=0, max_length=1024, strict=True)]
# ==================================================================
# ============================= Script types =======================
# ==================================================================
# ---------------------------- Action type -------------------------
class CommandString(FormatString):
_min_length = 1
# All unicode except the [Cc] (control characters) category
_regex = f"(?-m:^[^{_Cc_characters}]+\\Z)"
def __new__(cls, value: str, *, context: ModelParsingContextInterface = ModelParsingContext()):
return super().__new__(cls, value, context=context)
class ArgString(FormatString):
# All unicode except the [Cc] (control characters) category, plus the line
# breaks LF (\n) and CR (\r) so multi-line inline scripts can be passed as
# arguments (e.g. `python -c "<multi-line>"`). Matches the openjd-rs
# reference, which accepts LF/CR (but not TAB or other control chars) in
# args with no extension required.
_regex = f"(?-m:^(?:[^{_Cc_characters}]|[\r\n])*\\Z)"
def __new__(cls, value: str, *, context: ModelParsingContextInterface = ModelParsingContext()):
return super().__new__(cls, value, context=context)
class CancelationMode(str, Enum):
NOTIFY_THEN_TERMINATE = "NOTIFY_THEN_TERMINATE"
TERMINATE = "TERMINATE"
NotifyPeriodType = Annotated[int, Field(ge=1, le=600)]
def _validate_notify_period_value(
v: Any, info: ValidationInfo
) -> Optional[Union[int, FormatString]]:
"""Shared notifyPeriodInSeconds validation for
CancelationMethodNotifyThenTerminate and CancelationMethodDeferred."""
if v is None:
return v
context = cast(Optional[ModelParsingContext], info.context)
if isinstance(v, str):
if context and "FEATURE_BUNDLE_1" not in context.extensions:
# Try to parse as int, fail if not
try:
return int(v)
except ValueError:
raise ValueError(
"notifyPeriodInSeconds as a format string requires the FEATURE_BUNDLE_1 extension."
)
return validate_int_fmtstring_field(v, ge=1, context=context)
if isinstance(v, int):
if v < 1 or v > 600:
raise ValueError("notifyPeriodInSeconds must be between 1 and 600")
return v
return v
class CancelationMethodNotifyThenTerminate(OpenJDModel_v2023_09):
"""Notify-then-terminate cancelation mode for an Action.
On Posix systems — Send a SIGTERM, followed by waiting for the notify period in
seconds, and then sending SIGKILL to the entire process tree if the command is
still running.
On Windows systems — Send a CTRL_C, followed by waiting for the notify period in
seconds, and then Terminating the entire process tree if the command is still running.
Prior to sending the first signal, a file called cancel.info is written to the session
working directory. The contents of this file provide an ISO 8601 time in UTC, in the form
<year>-<month>-<day>T<hour>:<minute>:<second>Z,
at which the notify period will end. The format of this file is:
```
NotifyEnd = <yyyy>-<mm>-<dd>T<hh>:<mm>:<ss>Z
```
Attributes:
mode ("NOTIFY_THEN_TERMINATE"): The mode of the cancelation to use.
notifyPeriodInSeconds (Optional[int]): Defines the maximum number of seconds between
the two signals. It is possible that the actual duration allowed in a particular
cancel event will be less than this amount if circumstances warrant.
Maximum value: 600
Defaults:
120 for onRun StepScript Action
30 for all other Actions
"""
mode: Literal[CancelationMode.NOTIFY_THEN_TERMINATE]
notifyPeriodInSeconds: Optional[Union[NotifyPeriodType, FormatString]] = None # noqa: N815
_job_creation_metadata = JobCreationMetadata(resolve_fields={"notifyPeriodInSeconds"})
@field_validator("notifyPeriodInSeconds", mode="before")
@classmethod
def _validate_notify_period(
cls, v: Any, info: ValidationInfo
) -> Optional[Union[int, FormatString]]:
return _validate_notify_period_value(v, info)
class CancelationMethodTerminate(OpenJDModel_v2023_09):
"""Terminate cancelation mode for an Action.
On Posix systems — Send SIGKILL to the entire process tree when a cancel is requested.
On Windows systems - Terminate the entire process tree when a cancel is requested.
Attributes:
mode ("TERMINATE"): The mode of the cancelation to use.
"""
mode: Literal[CancelationMode.TERMINATE]
class CancelationMethodDeferred(OpenJDModel_v2023_09):
"""A cancelation whose ``mode`` is a format string, resolved at run
time (Template Schemas 5.3, FEATURE_BUNDLE_1 extension).
What is the problem this solves?
Format strings in general are *already* delay-processed: when a template
says ``args: ["{{WrappedAction.Command}}"]``, the parser just stores
"this is a format string" and the value gets resolved much later, inside
a running session, right before the action launches — that's when the
runtime seeds the ``WrappedAction.*`` variables from the action being
wrapped. "Resolve later" is the normal pipeline for every other field.
``mode`` is different because it isn't a normal value field — it's the
*schema selector*. The parser needs to know TERMINATE vs
NOTIFY_THEN_TERMINATE at parse time to decide what shape of object it's
even reading (only one of them allows ``notifyPeriodInSeconds``). So the
"which shape?" decision happens at parse time, but a forwarded value
like ``mode: "{{WrappedAction.Cancelation.Mode}}"`` only exists at run
time — that mismatch made round-trip cancelation forwarding in RFC 0008
wrap hooks impossible (pydantic's discriminated union rejected the
template with "does not match any of the expected tags").
The fix is this class: the parser accepts a format string in ``mode``
as a third, "decided later" state (gated on the FEATURE_BUNDLE_1
extension), and the shape decision moves to resolution time, right
before the action runs:
1. The runtime seeds ``WrappedAction.Cancelation.Mode`` from the
wrapped action (``"TERMINATE"``, ``"NOTIFY_THEN_TERMINATE"``, or
``None``).
2. It resolves the ``mode:`` expression against that.
3. ``"TERMINATE"``/``"NOTIFY_THEN_TERMINATE"`` — the cancelation block
now acts as that method, and its sibling fields are validated
against that shape. ``None`` (null, whole-field expressions only) —
the whole ``cancelation:`` block is treated as never written.
Anything else — the action fails.
Static validation is *not* deferred: at parse time the validator still
checks the expression is well-formed and that ``WrappedAction.*`` is
only referenced inside wrap hooks. Any format string is accepted —
normal interpolation like ``"{{Prefix}}_THEN_TERMINATE"`` is permitted;
only the resolved value is constrained. You just can't know *which* of
the two modes it'll be until the wrapped action is in front of you —
which is inherent to forwarding: the same wrap environment gets reused
across many steps whose cancelation settings differ.
Mirrors ``CancelationMode::DeferredMode`` in openjd-rs. See
openjd-specifications Template Schemas 5.3 and RFC 0008 "Cancelation
behavior".
Attributes:
mode (FormatString): A format string resolving to "TERMINATE" or
"NOTIFY_THEN_TERMINATE"; a whole-field interpolation expression
may also resolve to null.
notifyPeriodInSeconds (Optional[Union[int, FormatString]]): As on
CancelationMethodNotifyThenTerminate; only meaningful when the
mode resolves to NOTIFY_THEN_TERMINATE, and must resolve to
null when the mode resolves to TERMINATE.
"""
mode: FormatString
notifyPeriodInSeconds: Optional[Union[NotifyPeriodType, FormatString]] = None # noqa: N815
_job_creation_metadata = JobCreationMetadata(resolve_fields={"notifyPeriodInSeconds"})
@field_validator("mode", mode="before")
@classmethod
def _validate_mode(cls, v: Any, info: ValidationInfo) -> Any:
if isinstance(v, str):
context = cast(Optional[ModelParsingContext], info.context)
if context and "FEATURE_BUNDLE_1" not in context.extensions:
raise ValueError(
"a format string in cancelation mode requires the FEATURE_BUNDLE_1 extension."
)
# Any format string is permitted (normal format string
# behavior, Template Schemas 5.3); the resolved value is
# checked against the two mode names at run time. Only a
# whole-field expression additionally gets string? null
# semantics (a null result drops the cancelation object).
return v
@field_validator("notifyPeriodInSeconds", mode="before")
@classmethod
def _validate_notify_period(
cls, v: Any, info: ValidationInfo
) -> Optional[Union[int, FormatString]]:
return _validate_notify_period_value(v, info)
def _cancelation_discriminator(v: Any) -> Optional[str]:
"""Callable discriminator for the cancelation union: routes the two
literal modes to their fixed-shape classes and a format-string mode to
:class:`CancelationMethodDeferred` (see that class's docstring for why
the mode decision can be deferred at all)."""
mode = v.get("mode") if isinstance(v, dict) else getattr(v, "mode", None)
if isinstance(mode, CancelationMode):
mode = mode.value
if isinstance(mode, str):
if mode == CancelationMode.NOTIFY_THEN_TERMINATE.value:
return "notify_then_terminate"
if mode == CancelationMode.TERMINATE.value:
return "terminate"
if "{{" in mode:
return "deferred"
if isinstance(v, CancelationMethodNotifyThenTerminate):
return "notify_then_terminate"
if isinstance(v, CancelationMethodTerminate):
return "terminate"
if isinstance(v, CancelationMethodDeferred):
return "deferred"
return None
CancelationMethod = Annotated[
Union[
Annotated[CancelationMethodNotifyThenTerminate, Tag("notify_then_terminate")],
Annotated[CancelationMethodTerminate, Tag("terminate")],
Annotated[CancelationMethodDeferred, Tag("deferred")],
],
Discriminator(_cancelation_discriminator),
]
ArgListType = Annotated[list[ArgString], Field(min_length=1)]
# WRAP_ACTIONS (RFC 0008) wrap-hook field names on EnvironmentActions.
_WRAP_ACTION_FIELDS = ("onWrapEnvEnter", "onWrapTaskRun", "onWrapEnvExit")
# RFC 0008 single-wrap-layer rule. Mirrors the message emitted by openjd-rs
# (validate_v2023_09/wrap_actions.rs::SINGLE_WRAP_LAYER_MSG).
_SINGLE_WRAP_LAYER_MSG = (
"only one environment in the session stack may define any of onWrapEnvEnter, "
"onWrapTaskRun, onWrapEnvExit (RFC 0008)."
)
def _env_defines_wrap_hook(env: Any) -> bool:
"""True if the given Environment's script defines any WRAP_ACTIONS hook.
Used by the single-wrap-layer validation to count the wrap-defining
environments reachable in a session stack.
"""
script = getattr(env, "script", None)
actions = getattr(script, "actions", None) if script is not None else None
if actions is None:
return False
return any(getattr(actions, name, None) is not None for name in _WRAP_ACTION_FIELDS)
# RFC 0008 wrapped-context variable namespaces and where each may be
# referenced. `WrappedAction.*` is available in all three wrap hooks;
# `WrappedEnv.*` only in the env-enter/exit hooks; `WrappedStep.*` only in the
# task-run hook. None of them may be referenced outside the wrap hooks.
_WRAPPED_NAMESPACES = ("WrappedAction", "WrappedEnv", "WrappedStep")
_WRAP_HOOK_ALLOWED_NAMESPACES = {
"onWrapEnvEnter": {"WrappedAction", "WrappedEnv"},
"onWrapEnvExit": {"WrappedAction", "WrappedEnv"},
"onWrapTaskRun": {"WrappedAction", "WrappedStep"},
}
def _action_referenced_namespaces(action: Any) -> set[str]:
"""Collect the set of wrapped-context namespaces (``WrappedAction`` /
``WrappedEnv`` / ``WrappedStep``) referenced by an Action's format strings.
Inspects every FormatString-bearing field of the Action: ``command``, each
of ``args``, and ``timeout`` (which is a FormatString under the
FEATURE_BUNDLE_1 extension, and a plain int otherwise — non-FormatString
values are skipped).
"""
referenced: set[str] = set()
if action is None:
return referenced
format_strings = [
getattr(action, "command", None),
*(getattr(action, "args", None) or []),
getattr(action, "timeout", None),
]
for fs in format_strings:
if not isinstance(fs, FormatString):
continue
for expr_info in fs.expressions:
expr = expr_info.expression
if expr is None:
continue
for symbol in expr.accessed_symbols:
namespace = symbol.split(".", 1)[0]
if namespace in _WRAPPED_NAMESPACES:
referenced.add(namespace)
return referenced
class Action(OpenJDModel_v2023_09):
"""An Action to run.
Attributes:
command (FormatString): The command/executable that will be run.
args (Optional[list[FormatString]]): The arguments that are provided to the command
when it is run.
timeout (Optional[int]): Maximum allowed runtime of the Action in seconds.
Can be a format string with FEATURE_BUNDLE_1 extension.
Default: No timeout
cancelation (Optional[CancelationMethod]): If defined, provides details
regarding how this action should be canceled. One of
CancelationMethodNotifyThenTerminate, CancelationMethodTerminate, or
CancelationMethodDeferred (a format-string mode resolved
at run time; FEATURE_BUNDLE_1).
Default: CancelationMethodTerminate
"""
command: CommandString
args: Optional[ArgListType] = None
timeout: Optional[Union[PositiveInt, FormatString]] = None
cancelation: Optional[CancelationMethod] = None
_job_creation_metadata = JobCreationMetadata(resolve_fields={"timeout"})
@field_validator("timeout", mode="before")
@classmethod
def _validate_timeout(cls, v: Any, info: ValidationInfo) -> Optional[Union[int, FormatString]]:
if v is None:
return v
context = cast(Optional[ModelParsingContext], info.context)
if isinstance(v, str):
if context and "FEATURE_BUNDLE_1" not in context.extensions:
# Try to parse as int, fail if not
try:
return int(v)
except ValueError:
raise ValueError(
"timeout as a format string requires the FEATURE_BUNDLE_1 extension."
)
return validate_int_fmtstring_field(v, ge=1, context=context)
if isinstance(v, int):
if v < 1:
raise ValueError("timeout must be a positive integer")
return v
return v
class StepActions(OpenJDModel_v2023_09):
"""The Actions for Tasks of a Step.
Attributes:
onRun (Action): Action to run when running a single Task.
"""
onRun: Action # noqa: N815
class EnvironmentActions(OpenJDModel_v2023_09):
"""The Actions to run at various stages of running an Environment.
Attributes:
onEnter (Optional[Action]): Action to run when entering the environment
as part of a Session.
onExit (Optional[Action]): Action to run when exiting the environment
in a Session.
onWrapEnvEnter (Optional[Action]): WRAP_ACTIONS — runs instead of the
onEnter of every inner environment while this environment is active.
onWrapTaskRun (Optional[Action]): WRAP_ACTIONS — runs instead of every
task's onRun while this environment is active.
onWrapEnvExit (Optional[Action]): WRAP_ACTIONS — runs instead of the
onExit of every inner environment while this environment is active.
Note: Must define at least one of onEnter or onExit (or, with the
WRAP_ACTIONS extension, the wrap actions). The three wrap actions are
all-or-nothing and require the WRAP_ACTIONS extension (which itself
requires EXPR).
"""
onEnter: Optional[Action] = Field(None) # noqa: N815
onExit: Optional[Action] = Field(None) # noqa: N815
# WRAP_ACTIONS extension (RFC 0008). Gated in the validator below.
onWrapEnvEnter: Optional[Action] = Field(None) # noqa: N815
onWrapTaskRun: Optional[Action] = Field(None) # noqa: N815
onWrapEnvExit: Optional[Action] = Field(None) # noqa: N815
@model_validator(mode="before")
@classmethod
def _requires_oneof(cls, values: dict[str, Any], info: ValidationInfo) -> dict[str, Any]:
"""A validator that runs on the model data before parsing.
Enforces, for the WRAP_ACTIONS extension (RFC 0008):
- wrap actions require the WRAP_ACTIONS extension to be declared;
- WRAP_ACTIONS requires the EXPR extension (hard prerequisite);
- the three wrap actions are all-or-nothing.
Otherwise preserves the legacy "must define onEnter or onExit" rule.
"""
if not isinstance(values, dict):
raise ValueError("Expected a dictionary of values")
context = cast(Optional[ModelParsingContext], info.context) if info else None
extensions = context.extensions if context else set()
wrap_values = {name: values.get(name) for name in _WRAP_ACTION_FIELDS}
any_wrap = any(v is not None for v in wrap_values.values())
if any_wrap:
# Extension gating is a template-decode concern and only applies
# when a parsing context is present. During job instantiation
# (create_job re-validates the model without a ModelParsingContext)
# the template has already been validated at decode time, so the
# extension-requirement checks are skipped then -- mirroring the
# `if context` guard the other extension gates in this module use.
if context is not None:
if "WRAP_ACTIONS" not in extensions:
raise ValueError(
"The onWrapEnvEnter, onWrapTaskRun, and onWrapEnvExit actions "
"require the WRAP_ACTIONS extension."
)
if "EXPR" not in extensions:
raise ValueError("The WRAP_ACTIONS extension requires the EXPR extension.")
if not all(v is not None for v in wrap_values.values()):
raise ValueError(
"When any wrap action is defined, all of onWrapEnvEnter, "
"onWrapTaskRun, and onWrapEnvExit must be defined."
)
# A wrap environment with the three hooks satisfies the
# "at least one action" requirement.
return values
on_enter = values.get("onEnter")
on_exit = values.get("onExit")
if on_enter is None and on_exit is None:
raise ValueError("Must define one of: onEnter or onExit")
return values
@model_validator(mode="after")
def _validate_wrapped_variable_scope(self, info: ValidationInfo) -> Self:
# RFC 0008 scope rule: WrappedAction.* may be referenced only in the
# three wrap hooks; WrappedEnv.* only in onWrapEnvEnter/onWrapEnvExit;
# WrappedStep.* only in onWrapTaskRun. None of them may appear in the
# ordinary onEnter/onExit actions. Schedulers must reject templates
# that violate this; mirrors openjd-rs (which enforces it via its
# per-scope function/symbol library split).
context = cast(Optional[ModelParsingContext], info.context) if info else None
extensions = context.extensions if context else set()
if "EXPR" not in extensions:
# Without EXPR the wrapped variables are never resolvable symbols,
# and the format strings carry no accessed-symbol set to inspect.
return self
errors = list[InitErrorDetails]()
for field_name in ("onEnter", "onExit", *_WRAP_ACTION_FIELDS):
action = getattr(self, field_name, None)
if action is None:
continue
allowed = _WRAP_HOOK_ALLOWED_NAMESPACES.get(field_name, set())
referenced = _action_referenced_namespaces(action)
for namespace in sorted(referenced - allowed):
errors.append(
InitErrorDetails(
type="value_error",
loc=(field_name,),
ctx={
"error": ValueError(
f"The {namespace}.* variables may not be referenced in "
f"{field_name} (RFC 0008)."
)
},
input=action,
)
)
if errors:
raise ValidationError.from_exception_data(self.__class__.__name__, errors)
return self
# --------------------- Embedded Files type -------------------------
class EmbeddedFileTypes(str, Enum):
TEXT = "TEXT"
class EndOfLine(str, Enum):
"""Line ending style for embedded files."""
AUTO = "AUTO"
LF = "LF"
CRLF = "CRLF"
# TODO - regex of allowable filename characters
Filename = Annotated[str, StringConstraints(min_length=1, max_length=256, strict=True)]
class DataString(FormatString):
_min_length = 1
def __new__(cls, value: str, *, context: ModelParsingContextInterface = ModelParsingContext()):
return super().__new__(cls, value, context=context)
class EmbeddedFileText(OpenJDModel_v2023_09):
"""A plain text file embedded directly into the Job Template.
This file is materialized to a subdirectory of a Session's working directory
when running a corresponding Action in the Session.
Attributes:
name (Identifier): A name by which the embedded file is referenced.
type ("TEXT"): The type of the emdedded file: plain text.
filename (Optional[str]): The filename to write the file as.
Default: Randomly generated filename.
runnable (Optional[bool]): A True value indicates that the written file
will have its execute-permissions set.
Default: False
data (FormatString): The text data to write to the file.
endOfLine (Optional[EndOfLine]): The line endings that the embedded file will have when
written to disk. If AUTO the embedded file will have the default line endings of the
host operating system. Requires FEATURE_BUNDLE_1 extension.
Default: AUTO
"""
name: Identifier
type: Literal[EmbeddedFileTypes.TEXT]
data: DataString
filename: Optional[Filename] = None
runnable: Optional[StrictBool] = None
endOfLine: Optional[EndOfLine] = None # noqa: N815
_template_variable_definitions = DefinesTemplateVariables(
defines={TemplateVariableDef(prefix="File.", resolves=ResolutionScope.SESSION)},
field="name",
)
_template_variable_sources = {
"__export__": {"__self__"},
"data": {"__self__"},
}
@field_validator("name")
@classmethod
def _validate_name(cls, v: str, info: ValidationInfo) -> str:
context = cast(Optional[ModelParsingContext], info.context)
max_len = 512 if context and "FEATURE_BUNDLE_1" in context.extensions else 64
if len(v) > max_len:
raise ValueError(f"name must be at most {max_len} characters long")
return v
@field_validator("filename")
@classmethod
def _validate_filename(cls, v: Optional[Filename], info: ValidationInfo) -> Optional[Filename]:
if v is None:
return v
if "/" in v or "\\" in v:
raise ValueError(
"filename must be a basename only and cannot contain path separators ('/' or '\\\\')"
)
context = cast(Optional[ModelParsingContext], info.context)
max_len = 256 if context and "FEATURE_BUNDLE_1" in context.extensions else 64
if len(v) > max_len:
raise ValueError(f"String must be at most {max_len} characters long")
return v
@field_validator("endOfLine")
@classmethod
def _validate_end_of_line(
cls, v: Optional[EndOfLine], info: ValidationInfo
) -> Optional[EndOfLine]:
if v is None:
return v
context = cast(Optional[ModelParsingContext], info.context)
# Skip extension check if no context (e.g., during job creation from validated template)
if context and "FEATURE_BUNDLE_1" not in context.extensions:
raise ValueError("The endOfLine property requires the FEATURE_BUNDLE_1 extension.")
return v
# --------------------- Script types ----------------------------
EmbeddedFiles = Annotated[list[EmbeddedFileText], Field(min_length=1)]
class ScriptInterpreter(str, Enum):
"""Script interpreter types for SimpleAction syntax sugar."""
PYTHON = "python"
BASH = "bash"
CMD = "cmd"
POWERSHELL = "powershell"
NODE = "node"
LET_MAX_BINDINGS = 50
_LET_NAME_RE = re.compile(r"^[a-z_][A-Za-z0-9_]*$")
def parse_let_bindings(value: Any) -> list[tuple[str, str]]:
"""Parse a ``let`` field value (list of ``"name = expression"`` strings)
into ``(name, expression)`` pairs. Raises ValueError on malformed input.
"""
if not isinstance(value, list):
raise ValueError("'let' must be a list of 'name = expression' bindings.")
result: list[tuple[str, str]] = []
for binding in value:
if not isinstance(binding, str):
raise ValueError("Each 'let' binding must be a 'name = expression' string.")
name, sep, expr = binding.partition("=")
if not sep:
raise ValueError(
f"A 'let' binding must be of the form 'name = expression': {binding!r}"
)
name = name.strip()
expr = expr.strip()
if not _LET_NAME_RE.match(name):
raise ValueError(f"A 'let' binding name must be a valid identifier: {name!r}")
if not expr:
raise ValueError(f"A 'let' binding must define an expression: {binding!r}")
result.append((name, expr))
return result
def validate_let_field(value: Any, info: ValidationInfo, *, simple_action: bool = False) -> Any:
"""Validate a ``let`` field: EXPR (and FEATURE_BUNDLE_1 for SimpleAction)
gating, non-empty, at most ``LET_MAX_BINDINGS``, each binding parses, and
unique names. Symbol-reference and shadow rules are validated separately by
the variable-reference prevalidator.
"""
if value is None:
return value
context = cast(Optional[ModelParsingContext], info.context)
if context and "EXPR" not in context.extensions:
raise ValueError("The 'let' field requires the EXPR extension.")
if simple_action and context and "FEATURE_BUNDLE_1" not in context.extensions:
raise ValueError("A SimpleAction 'let' requires the FEATURE_BUNDLE_1 extension.")
if isinstance(value, list) and len(value) == 0:
raise ValueError("'let' must define at least one binding.")
if isinstance(value, list) and len(value) > LET_MAX_BINDINGS:
raise ValueError(f"'let' must define at most {LET_MAX_BINDINGS} bindings.")
bindings = parse_let_bindings(value)
names = [name for name, _ in bindings]
if len(names) != len(set(names)):
raise ValueError("'let' binding names must be unique.")
return value
class SimpleAction(OpenJDModel_v2023_09):
"""Syntax sugar for a script action with a specific interpreter.
This is only available with the FEATURE_BUNDLE_1 extension.
Attributes:
script (DataString): The script content to execute.
args (Optional[list[ArgString]]): Additional arguments to pass to the interpreter.
timeout (Optional[Union[int, FormatString]]): Maximum allowed runtime in seconds.
Can be a format string.
cancelation (Optional[CancelationMethod]): How to cancel the action.
"""
script: DataString
args: Optional[ArgListType] = None
timeout: Optional[Union[PositiveInt, FormatString]] = None
cancelation: Optional[CancelationMethod] = None
let: Optional[list[str]] = None
# SimpleAction is syntax sugar that resolves to a StepScript (TASK scope),
# so it sees the same session-scope variables, and its `let` names (in
# __self__) are visible to its script and args.
_template_variable_scope = ResolutionScope.TASK
_template_variable_definitions = DefinesTemplateVariables(
inject={
f"|{ValueReferenceConstants.WORKING_DIRECTORY.value}",
f"|{ValueReferenceConstants.HAS_PATH_MAPPING_RULES.value}",
f"|{ValueReferenceConstants.PATH_MAPPING_RULES_FILE.value}",
},
)
_template_variable_sources = {
"script": {"__self__"},
"args": {"__self__"},
}
@field_validator("let")
@classmethod
def _validate_let(cls, v: Any, info: ValidationInfo) -> Any:
return validate_let_field(v, info, simple_action=True)
@field_validator("timeout", mode="before")
@classmethod
def _validate_timeout(cls, v: Any, info: ValidationInfo) -> Optional[Union[int, FormatString]]:
if v is None:
return v
context = cast(Optional[ModelParsingContext], info.context)
if isinstance(v, str):
# SimpleAction always requires FEATURE_BUNDLE_1, so format strings are allowed
return validate_int_fmtstring_field(v, ge=1, context=context)
if isinstance(v, int):
if v < 1:
raise ValueError("timeout must be a positive integer")
return v
return v
class StepScript(OpenJDModel_v2023_09):
"""The Step Script is the information on what Actions to perform when running
a Task for a Step.
Attributes:
embeddedFiles (Optional[list[EmbeddedFileText]]): List of text files embedded
into the script. These will be written to disk prior to running each of the
Actions in the script.
actions (StepActions): The actions to run when running a Task for the Step.
"""
actions: StepActions
embeddedFiles: Optional[EmbeddedFiles] = None # noqa: N815
let: Optional[list[str]] = None
_template_variable_scope = ResolutionScope.TASK
_template_variable_definitions = DefinesTemplateVariables(
symbol_prefix="|Task.",
inject={
f"|{ValueReferenceConstants.WORKING_DIRECTORY.value}",
f"|{ValueReferenceConstants.HAS_PATH_MAPPING_RULES.value}",
f"|{ValueReferenceConstants.PATH_MAPPING_RULES_FILE.value}",
},
)
_template_variable_sources = {
"actions": {"embeddedFiles", "__self__"},
"embeddedFiles": {"embeddedFiles", "__self__"},
}
@field_validator("let")
@classmethod
def _validate_let(cls, v: Any, info: ValidationInfo) -> Any:
return validate_let_field(v, info)
@field_validator("embeddedFiles")
@classmethod
def _unique_names(cls, v: Optional[EmbeddedFiles]) -> Optional[EmbeddedFiles]: