/
repository_definition.py
1313 lines (1082 loc) · 50.4 KB
/
repository_definition.py
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
from abc import ABC, abstractmethod
from inspect import isfunction
from types import FunctionType
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generic,
List,
Mapping,
Optional,
Type,
TypeVar,
Union,
cast,
)
import dagster._check as check
from dagster.core.errors import DagsterInvalidDefinitionError, DagsterInvariantViolationError
from dagster.utils import merge_dicts
from .events import AssetKey
from .executor_definition import ExecutorDefinition
from .graph_definition import GraphDefinition, SubselectedGraphDefinition
from .job_definition import JobDefinition
from .partition import PartitionScheduleDefinition, PartitionSetDefinition
from .pipeline_definition import PipelineDefinition
from .schedule_definition import ScheduleDefinition
from .sensor_definition import SensorDefinition
from .source_asset import SourceAsset
from .unresolved_asset_job_definition import UnresolvedAssetJobDefinition
from .utils import check_valid_name
if TYPE_CHECKING:
from dagster.core.definitions import AssetGroup
VALID_REPOSITORY_DATA_DICT_KEYS = {
"pipelines",
"partition_sets",
"schedules",
"sensors",
"jobs",
}
RepositoryLevelDefinition = TypeVar(
"RepositoryLevelDefinition",
PipelineDefinition,
JobDefinition,
PartitionSetDefinition,
ScheduleDefinition,
SensorDefinition,
)
class _CacheingDefinitionIndex(Generic[RepositoryLevelDefinition]):
def __init__(
self,
definition_class: Type[RepositoryLevelDefinition],
definition_class_name: str,
definition_kind: str,
definitions: Mapping[
str, Union[RepositoryLevelDefinition, Callable[[], RepositoryLevelDefinition]]
],
validation_fn: Callable[[RepositoryLevelDefinition], RepositoryLevelDefinition],
lazy_definitions_fn: Optional[Callable[[], List[RepositoryLevelDefinition]]] = None,
):
"""
Args:
definitions: A dictionary of definition names to definitions or functions that load
definitions.
lazy_definitions_fn: A function for loading a list of definitions whose names are not
even known until loaded.
"""
for key, definition in definitions.items():
check.invariant(
isinstance(definition, definition_class) or callable(definition),
"Bad definition for {definition_kind} {key}: must be {definition_class_name} or "
"callable, got {type_}".format(
definition_kind=definition_kind,
key=key,
definition_class_name=definition_class_name,
type_=type(definition),
),
)
self._definition_class: Type[RepositoryLevelDefinition] = definition_class
self._definition_class_name = definition_class_name
self._definition_kind = definition_kind
self._validation_fn: Callable[
[RepositoryLevelDefinition], RepositoryLevelDefinition
] = validation_fn
self._definitions: Mapping[
str, Union[RepositoryLevelDefinition, Callable[[], RepositoryLevelDefinition]]
] = definitions
self._definition_cache: Dict[str, RepositoryLevelDefinition] = {}
self._definition_names: Optional[List[str]] = None
self._lazy_definitions_fn: Callable[
[], List[RepositoryLevelDefinition]
] = lazy_definitions_fn or (lambda: [])
self._lazy_definitions: Optional[List[RepositoryLevelDefinition]] = None
self._all_definitions: Optional[List[RepositoryLevelDefinition]] = None
def _get_lazy_definitions(self) -> List[RepositoryLevelDefinition]:
if self._lazy_definitions is None:
self._lazy_definitions = self._lazy_definitions_fn()
for definition in self._lazy_definitions:
self._validate_and_cache_definition(definition, definition.name)
return self._lazy_definitions
def get_definition_names(self) -> List[str]:
if self._definition_names:
return self._definition_names
lazy_names = []
for definition in self._get_lazy_definitions():
strict_definition = self._definitions.get(definition.name)
if strict_definition:
check.invariant(
strict_definition == definition,
f"Duplicate definition found for {definition.name}",
)
else:
lazy_names.append(definition.name)
self._definition_names = list(self._definitions.keys()) + lazy_names
return self._definition_names
def has_definition(self, definition_name: str) -> bool:
check.str_param(definition_name, "definition_name")
return definition_name in self.get_definition_names()
def get_all_definitions(self) -> List[RepositoryLevelDefinition]:
if self._all_definitions is not None:
return self._all_definitions
self._all_definitions = list(
sorted(
map(self.get_definition, self.get_definition_names()),
key=lambda definition: definition.name,
)
)
return self._all_definitions
def get_definition(self, definition_name: str) -> RepositoryLevelDefinition:
check.str_param(definition_name, "definition_name")
if not self.has_definition(definition_name):
raise DagsterInvariantViolationError(
"Could not find {definition_kind} '{definition_name}'. Found: "
"{found_names}.".format(
definition_kind=self._definition_kind,
definition_name=definition_name,
found_names=", ".join(
[
"'{found_name}'".format(found_name=found_name)
for found_name in self.get_definition_names()
]
),
)
)
if definition_name in self._definition_cache:
return self._definition_cache[definition_name]
definition_source = self._definitions[definition_name]
if isinstance(definition_source, self._definition_class):
self._definition_cache[definition_name] = self._validation_fn(definition_source)
return definition_source
else:
definition = cast(Callable, definition_source)()
self._validate_and_cache_definition(definition, definition_name)
return definition
def _validate_and_cache_definition(
self, definition: RepositoryLevelDefinition, definition_dict_key: str
):
check.invariant(
isinstance(definition, self._definition_class),
"Bad constructor for {definition_kind} {definition_name}: must return "
"{definition_class_name}, got value of type {type_}".format(
definition_kind=self._definition_kind,
definition_name=definition_dict_key,
definition_class_name=self._definition_class_name,
type_=type(definition),
),
)
check.invariant(
definition.name == definition_dict_key,
"Bad constructor for {definition_kind} '{definition_name}': name in "
"{definition_class_name} does not match: got '{definition_def_name}'".format(
definition_kind=self._definition_kind,
definition_name=definition_dict_key,
definition_class_name=self._definition_class_name,
definition_def_name=definition.name,
),
)
self._definition_cache[definition_dict_key] = self._validation_fn(definition)
class RepositoryData(ABC):
"""
Users should usually rely on the :py:func:`@repository <repository>` decorator to create new
repositories, which will in turn call the static constructors on this class. However, users may
subclass :py:class:`RepositoryData` for fine-grained control over access to and lazy creation
of repository members.
"""
@abstractmethod
def get_all_pipelines(self) -> List[PipelineDefinition]:
"""Return all pipelines/jobs in the repository as a list.
Returns:
List[PipelineDefinition]: All pipelines/jobs in the repository.
"""
def get_all_jobs(self) -> List[JobDefinition]:
"""Return all jobs in the repository as a list.
Returns:
List[JobDefinition]: All jobs in the repository.
"""
return [job for job in self.get_all_pipelines() if isinstance(job, JobDefinition)]
def get_pipeline_names(self) -> List[str]:
"""Get the names of all pipelines/jobs in the repository.
Returns:
List[str]
"""
return [pipeline_def.name for pipeline_def in self.get_all_pipelines()]
def get_job_names(self) -> List[str]:
"""Get the names of all jobs in the repository.
Returns:
List[str]
"""
return [job_def.name for job_def in self.get_all_jobs()]
def has_pipeline(self, pipeline_name: str) -> bool:
"""Check if a pipeline/job with a given name is present in the repository.
Args:
pipeline_name (str): The name of the pipeline/job.
Returns:
bool
"""
return pipeline_name in self.get_pipeline_names()
def has_job(self, job_name: str) -> bool:
"""Check if a job with a given name is present in the repository.
Args:
job_name (str): The name of the job.
Returns:
bool
"""
return job_name in self.get_job_names()
def get_pipeline(self, pipeline_name) -> PipelineDefinition:
"""Get a pipeline/job by name.
Args:
pipeline_name (str): Name of the pipeline/job to retrieve.
Returns:
PipelineDefinition: The pipeline/job definition corresponding to the given name.
"""
pipelines_with_name = [
pipeline for pipeline in self.get_all_pipelines() if pipeline.name == pipeline_name
]
if not pipelines_with_name:
raise DagsterInvariantViolationError(
f"Could not find pipeline/job {pipeline_name} in repository"
)
return pipelines_with_name[0]
def get_job(self, job_name: str) -> JobDefinition:
"""Get a job by name.
Args:
job_name (str): Name of the job to retrieve.
Returns:
JobDefinition: The job definition corresponding to the given name.
"""
match = next(job for job in self.get_all_jobs() if job.name == job_name)
if match is None:
raise DagsterInvariantViolationError(f"Could not find job {job_name} in repository")
return match
def get_partition_set_names(self):
"""Get the names of all partition sets in the repository.
Returns:
List[str]
"""
return [partition_set.name for partition_set in self.get_all_partition_sets()]
def has_partition_set(self, partition_set_name: str) -> bool:
"""Check if a partition set with a given name is present in the repository.
Args:
partition_set_name (str): The name of the partition set.
Returns:
bool
"""
return partition_set_name in self.get_partition_set_names()
def get_all_partition_sets(self) -> List[PartitionSetDefinition]:
"""Return all partition sets in the repository as a list.
Returns:
List[PartitionSetDefinition]: All partition sets in the repository.
"""
return []
def get_partition_set(self, partition_set_name: str) -> PartitionSetDefinition:
"""Get a partition set by name.
Args:
partition_set_name (str): Name of the partition set to retrieve.
Returns:
PartitionSetDefinition: The partition set definition corresponding to the given name.
"""
partition_sets_with_name = [
partition_set
for partition_set in self.get_all_partition_sets()
if partition_set.name == partition_set_name
]
if not partition_sets_with_name:
raise DagsterInvariantViolationError(
f"Could not find partition set {partition_set_name} in repository"
)
return partition_sets_with_name[0]
def get_schedule_names(self) -> List[str]:
"""Get the names of all schedules in the repository.
Returns:
List[str]
"""
return [schedule.name for schedule in self.get_all_schedules()]
def get_all_schedules(self) -> List[ScheduleDefinition]:
"""Return all schedules in the repository as a list.
Returns:
List[ScheduleDefinition]: All pipelines in the repository.
"""
return []
def get_schedule(self, schedule_name: str) -> ScheduleDefinition:
"""Get a schedule by name.
args:
schedule_name (str): name of the schedule to retrieve.
Returns:
ScheduleDefinition: The schedule definition corresponding to the given name.
"""
schedules_with_name = [
schedule for schedule in self.get_all_schedules() if schedule.name == schedule_name
]
if not schedules_with_name:
raise DagsterInvariantViolationError(
f"Could not find schedule {schedule_name} in repository"
)
return schedules_with_name[0]
def has_schedule(self, schedule_name: str) -> bool:
return schedule_name in self.get_schedule_names()
def get_all_sensors(self) -> List[SensorDefinition]:
return []
def get_sensor_names(self) -> List[str]:
return [sensor.name for sensor in self.get_all_sensors()]
def get_sensor(self, sensor_name: str) -> SensorDefinition:
sensors_with_name = [
sensor for sensor in self.get_all_sensors() if sensor.name == sensor_name
]
if not sensors_with_name:
raise DagsterInvariantViolationError(
f"Could not find sensor {sensor_name} in repository"
)
return sensors_with_name[0]
def has_sensor(self, sensor_name: str) -> bool:
return sensor_name in self.get_sensor_names()
def get_source_assets_by_key(self) -> Mapping[AssetKey, SourceAsset]:
return {}
def load_all_definitions(self):
# force load of all lazy constructed code artifacts
self.get_all_pipelines()
self.get_all_jobs()
self.get_all_partition_sets()
self.get_all_schedules()
self.get_all_sensors()
self.get_source_assets_by_key()
T = TypeVar("T")
Resolvable = Callable[[], T]
class CachingRepositoryData(RepositoryData):
"""Default implementation of RepositoryData used by the :py:func:`@repository <repository>` decorator."""
_all_jobs: Optional[List[JobDefinition]]
_all_pipelines: Optional[List[PipelineDefinition]]
def __init__(
self,
pipelines: Mapping[str, Union[PipelineDefinition, Resolvable[PipelineDefinition]]],
jobs: Mapping[str, Union[JobDefinition, Resolvable[JobDefinition]]],
partition_sets: Mapping[
str, Union[PartitionSetDefinition, Resolvable[PartitionSetDefinition]]
],
schedules: Mapping[str, Union[ScheduleDefinition, Resolvable[ScheduleDefinition]]],
sensors: Mapping[str, Union[SensorDefinition, Resolvable[SensorDefinition]]],
source_assets_by_key: Mapping[AssetKey, SourceAsset],
):
"""Constructs a new CachingRepositoryData object.
You may pass pipeline, job, partition_set, and schedule definitions directly, or you may pass
callables with no arguments that will be invoked to lazily construct definitions when
accessed by name. This can be helpful for performance when there are many definitions in a
repository, or when constructing the definitions is costly.
Note that when lazily constructing a definition, the name of the definition must match its
key in its dictionary index, or a :py:class:`DagsterInvariantViolationError` will be thrown
at retrieval time.
Args:
pipelines (Mapping[str, Union[PipelineDefinition, Callable[[], PipelineDefinition]]]):
The pipeline definitions belonging to the repository.
jobs (Mapping[str, Union[JobDefinition, Callable[[], JobDefinition]]]):
The job definitions belonging to the repository.
partition_sets (Mapping[str, Union[PartitionSetDefinition, Callable[[], PartitionSetDefinition]]]):
The partition sets belonging to the repository.
schedules (Mapping[str, Union[ScheduleDefinition, Callable[[], ScheduleDefinition]]]):
The schedules belonging to the repository.
sensors (Mapping[str, Union[SensorDefinition, Callable[[], SensorDefinition]]]):
The sensors belonging to a repository.
source_assets_by_key (Mapping[AssetKey, SourceAsset]): The source assets belonging to a repository.
"""
check.mapping_param(
pipelines, "pipelines", key_type=str, value_type=(PipelineDefinition, FunctionType)
)
check.mapping_param(jobs, "jobs", key_type=str, value_type=(JobDefinition, FunctionType))
check.mapping_param(
partition_sets,
"partition_sets",
key_type=str,
value_type=(PartitionSetDefinition, FunctionType),
)
check.mapping_param(
schedules, "schedules", key_type=str, value_type=(ScheduleDefinition, FunctionType)
)
check.mapping_param(
sensors, "sensors", key_type=str, value_type=(SensorDefinition, FunctionType)
)
check.mapping_param(
source_assets_by_key, "source_assets_by_key", key_type=AssetKey, value_type=SourceAsset
)
self._pipelines = _CacheingDefinitionIndex(
PipelineDefinition,
"PipelineDefinition",
"pipeline",
pipelines,
self._validate_pipeline,
)
self._jobs = _CacheingDefinitionIndex(
JobDefinition,
"JobDefinition",
"job",
jobs,
self._validate_job,
)
self._schedules = _CacheingDefinitionIndex(
ScheduleDefinition,
"ScheduleDefinition",
"schedule",
schedules,
self._validate_schedule,
)
schedule_partition_sets = [
schedule.get_partition_set()
for schedule in self._schedules.get_all_definitions()
if isinstance(schedule, PartitionScheduleDefinition)
]
self._source_assets_by_key = source_assets_by_key
def load_partition_sets_from_pipelines() -> List[PartitionSetDefinition]:
job_partition_sets = []
for pipeline in self.get_all_pipelines():
if isinstance(pipeline, JobDefinition):
job_partition_set = pipeline.get_partition_set_def()
if job_partition_set:
# should only return a partition set if this was constructed using the job
# API, with a partitioned config
job_partition_sets.append(job_partition_set)
return job_partition_sets
self._partition_sets = _CacheingDefinitionIndex(
PartitionSetDefinition,
"PartitionSetDefinition",
"partition set",
merge_dicts(
{partition_set.name: partition_set for partition_set in schedule_partition_sets},
partition_sets,
),
self._validate_partition_set,
load_partition_sets_from_pipelines,
)
self._sensors = _CacheingDefinitionIndex(
SensorDefinition,
"SensorDefinition",
"sensor",
sensors,
self._validate_sensor,
)
# load all sensors to force validation
self._sensors.get_all_definitions()
self._all_pipelines = None
self._all_jobs = None
@staticmethod
def from_dict(repository_definitions: Dict[str, Dict[str, Any]]) -> "CachingRepositoryData":
"""Static constructor.
Args:
repository_definition (Dict[str, Dict[str, ...]]): A dict of the form:
{
'pipelines': Dict[str, Callable[[], PipelineDefinition]],
'jobs': Dict[str, Callable[[], JobDefinition]],
'partition_sets': Dict[str, Callable[[], PartitionSetDefinition]],
'schedules': Dict[str, Callable[[], ScheduleDefinition]]
}
This form is intended to allow definitions to be created lazily when accessed by name,
which can be helpful for performance when there are many definitions in a repository, or
when constructing the definitions is costly.
"""
check.dict_param(repository_definitions, "repository_definitions", key_type=str)
check.invariant(
set(repository_definitions.keys()).issubset(VALID_REPOSITORY_DATA_DICT_KEYS),
"Bad dict: must not contain keys other than {{{valid_keys}}}: found {bad_keys}.".format(
valid_keys=", ".join(
["'{key}'".format(key=key) for key in VALID_REPOSITORY_DATA_DICT_KEYS]
),
bad_keys=", ".join(
[
"'{key}'"
for key in repository_definitions.keys()
if key not in VALID_REPOSITORY_DATA_DICT_KEYS
]
),
),
)
for key in VALID_REPOSITORY_DATA_DICT_KEYS:
if key not in repository_definitions:
repository_definitions[key] = {}
duplicate_keys = set(repository_definitions["schedules"].keys()).intersection(
set(repository_definitions["sensors"].keys())
)
if duplicate_keys:
raise DagsterInvalidDefinitionError(
f"Duplicate definitions between schedules and sensors found for keys: {', '.join(duplicate_keys)}"
)
# merge jobs in to pipelines while they are just implemented as pipelines
for key, job in repository_definitions["jobs"].items():
if key in repository_definitions["pipelines"]:
raise DagsterInvalidDefinitionError(
f'Conflicting entries for name {key} in "jobs" and "pipelines".'
)
if isinstance(job, GraphDefinition):
repository_definitions["jobs"][key] = job.coerce_to_job()
elif isinstance(job, UnresolvedAssetJobDefinition):
repository_definitions["jobs"][key] = job.resolve(
# TODO: https://github.com/dagster-io/dagster/issues/8263
assets=[],
source_assets=[],
executor_def=None,
)
elif not isinstance(job, JobDefinition) and not isfunction(job):
raise DagsterInvalidDefinitionError(
f"Object mapped to {key} is not an instance of JobDefinition or GraphDefinition."
)
return CachingRepositoryData(**repository_definitions, source_assets_by_key={})
@classmethod
def from_list(
cls,
repository_definitions: List[
Union[
PipelineDefinition,
PartitionSetDefinition,
ScheduleDefinition,
SensorDefinition,
"AssetGroup",
GraphDefinition,
UnresolvedAssetJobDefinition,
]
],
default_executor_def: Optional[ExecutorDefinition] = None,
) -> "CachingRepositoryData":
"""Static constructor.
Args:
repository_definitions (List[Union[PipelineDefinition, PartitionSetDefinition, ScheduleDefinition, SensorDefinition, AssetGroup, GraphDefinition]]):
Use this constructor when you have no need to lazy load pipelines/jobs or other
definitions.
"""
from dagster.core.definitions import AssetGroup, AssetsDefinition
pipelines_or_jobs: Dict[str, Union[PipelineDefinition, JobDefinition]] = {}
coerced_graphs: Dict[str, JobDefinition] = {}
unresolved_jobs: Dict[str, UnresolvedAssetJobDefinition] = {}
partition_sets: Dict[str, PartitionSetDefinition] = {}
schedules: Dict[str, ScheduleDefinition] = {}
sensors: Dict[str, SensorDefinition] = {}
assets_defs: List[AssetsDefinition] = []
source_assets: List[SourceAsset] = []
combined_asset_group = None
for definition in repository_definitions:
if isinstance(definition, PipelineDefinition):
if (
definition.name in pipelines_or_jobs
and pipelines_or_jobs[definition.name] != definition
) or definition.name in unresolved_jobs:
raise DagsterInvalidDefinitionError(
"Duplicate {target_type} definition found for {target}".format(
target_type=definition.target_type, target=definition.describe_target()
)
)
if AssetGroup.is_base_job_name(definition.name):
raise DagsterInvalidDefinitionError(
f"Attempted to provide job called {definition.name} to repository, which "
"is a reserved name. Please rename the job."
)
pipelines_or_jobs[definition.name] = definition
elif isinstance(definition, PartitionSetDefinition):
if definition.name in partition_sets:
raise DagsterInvalidDefinitionError(
"Duplicate partition set definition found for partition set "
"{partition_set_name}".format(partition_set_name=definition.name)
)
partition_sets[definition.name] = definition
elif isinstance(definition, SensorDefinition):
if definition.name in sensors or definition.name in schedules:
raise DagsterInvalidDefinitionError(
f"Duplicate definition found for {definition.name}"
)
sensors[definition.name] = definition
elif isinstance(definition, ScheduleDefinition):
if definition.name in sensors or definition.name in schedules:
raise DagsterInvalidDefinitionError(
f"Duplicate definition found for {definition.name}"
)
schedules[definition.name] = definition
if isinstance(definition, PartitionScheduleDefinition):
partition_set_def = definition.get_partition_set()
if (
partition_set_def.name in partition_sets
and partition_set_def != partition_sets[partition_set_def.name]
):
raise DagsterInvalidDefinitionError(
"Duplicate partition set definition found for partition set "
"{partition_set_name}".format(partition_set_name=partition_set_def.name)
)
partition_sets[partition_set_def.name] = partition_set_def
elif isinstance(definition, GraphDefinition):
coerced = definition.coerce_to_job()
if coerced.name in pipelines_or_jobs:
raise DagsterInvalidDefinitionError(
"Duplicate {target_type} definition found for graph '{name}'".format(
target_type=coerced.target_type, name=coerced.name
)
)
pipelines_or_jobs[coerced.name] = coerced
coerced_graphs[coerced.name] = coerced
elif isinstance(definition, UnresolvedAssetJobDefinition):
if definition.name in pipelines_or_jobs or definition.name in unresolved_jobs:
raise DagsterInvalidDefinitionError(
"Duplicate definition found for unresolved job '{name}'".format(
name=definition.name
)
)
# we can only resolve these once we have all assets
unresolved_jobs[definition.name] = definition
elif isinstance(definition, AssetGroup):
if combined_asset_group:
combined_asset_group += definition
else:
combined_asset_group = definition
elif isinstance(definition, AssetsDefinition):
assets_defs.append(definition)
elif isinstance(definition, SourceAsset):
source_assets.append(definition)
else:
check.failed(f"Unexpected repository entry {definition}")
if assets_defs or source_assets:
if combined_asset_group is not None:
raise DagsterInvalidDefinitionError(
"A repository can't have both an AssetGroup and direct asset defs"
)
combined_asset_group = AssetGroup(
assets=assets_defs,
source_assets=source_assets,
executor_def=default_executor_def,
)
if combined_asset_group:
for job_def in combined_asset_group.get_base_jobs():
pipelines_or_jobs[job_def.name] = job_def
source_assets_by_key = {
source_asset.key: source_asset
for source_asset in combined_asset_group.source_assets
}
else:
source_assets_by_key = {}
for name, sensor_def in sensors.items():
if sensor_def.has_loadable_targets():
targets = sensor_def.load_targets()
for target in targets:
_process_and_validate_target(
sensor_def, coerced_graphs, unresolved_jobs, pipelines_or_jobs, target
)
for name, schedule_def in schedules.items():
if schedule_def.has_loadable_target():
target = schedule_def.load_target()
_process_and_validate_target(
schedule_def, coerced_graphs, unresolved_jobs, pipelines_or_jobs, target
)
# resolve all the UnresolvedAssetJobDefinitions using the full set of assets
for name, unresolved_job_def in unresolved_jobs.items():
if not combined_asset_group:
raise DagsterInvalidDefinitionError(
f"UnresolvedAssetJobDefinition {name} specified, but no AssetDefinitions exist "
"on the repository."
)
resolved_job = unresolved_job_def.resolve(
assets=combined_asset_group.assets,
source_assets=combined_asset_group.source_assets,
executor_def=default_executor_def,
)
pipelines_or_jobs[name] = resolved_job
pipelines: Dict[str, PipelineDefinition] = {}
jobs: Dict[str, JobDefinition] = {}
for name, pipeline_or_job in pipelines_or_jobs.items():
if isinstance(pipeline_or_job, JobDefinition):
jobs[name] = pipeline_or_job
else:
pipelines[name] = pipeline_or_job
if default_executor_def:
for name, job_def in jobs.items():
if not job_def._executor_def_specified: # pylint: disable=protected-access
jobs[name] = job_def.with_executor_def(default_executor_def)
return CachingRepositoryData(
pipelines=pipelines,
jobs=jobs,
partition_sets=partition_sets,
schedules=schedules,
sensors=sensors,
source_assets_by_key=source_assets_by_key,
)
def get_pipeline_names(self) -> List[str]:
"""Get the names of all pipelines/jobs in the repository.
Returns:
List[str]
"""
return self._pipelines.get_definition_names() + self.get_job_names()
def get_job_names(self) -> List[str]:
"""Get the names of all jobs in the repository.
Returns:
List[str]
"""
return self._jobs.get_definition_names()
def has_pipeline(self, pipeline_name: str) -> bool:
"""Check if a pipeline/job with a given name is present in the repository.
Args:
pipeline_name (str): The name of the pipeline/job.
Returns:
bool
"""
check.str_param(pipeline_name, "pipeline_name")
return self._pipelines.has_definition(pipeline_name) or self._jobs.has_definition(
pipeline_name
)
def has_job(self, job_name: str) -> bool:
"""Check if a job with a given name is present in the repository.
Args:
job_name (str): The name of the job.
Returns:
bool
"""
check.str_param(job_name, "job_name")
return self._jobs.has_definition(job_name)
def get_all_pipelines(self) -> List[PipelineDefinition]:
"""Return all pipelines/jobs in the repository as a list.
Note that this will construct any pipeline/job that has not yet been constructed.
Returns:
List[PipelineDefinition]: All pipelines/jobs in the repository.
"""
if self._all_pipelines is not None:
return self._all_pipelines
self._all_jobs = self._jobs.get_all_definitions()
pipelines: List[PipelineDefinition] = [
*self._pipelines.get_all_definitions(),
*self._all_jobs,
]
self._check_solid_defs(pipelines)
self._all_pipelines = pipelines
return self._all_pipelines
def get_all_jobs(self) -> List[JobDefinition]:
"""Return all jobs in the repository as a list.
Note that this will construct any job that has not yet been constructed.
Returns:
List[JobDefinition]: All jobs in the repository.
"""
if self._all_jobs is not None:
return self._all_jobs
# _check_solid_defs enforces that pipeline and graph definition names are
# unique within a repository. Loads pipelines in the line below to enforce
# pipeline/job/graph uniqueness.
self.get_all_pipelines()
# The `get_all_pipelines` call ensures _all_jobs is set.
return cast(List[JobDefinition], self._all_jobs)
def get_pipeline(self, pipeline_name: str) -> PipelineDefinition:
"""Get a pipeline/job by name.
If this pipeline/job has not yet been constructed, only this pipeline/job is constructed, and will
be cached for future calls.
Args:
pipeline_name (str): Name of the pipeline/job to retrieve.
Returns:
PipelineDefinition: The pipeline/job definition corresponding to the given name.
"""
check.str_param(pipeline_name, "pipeline_name")
if self._jobs.has_definition(pipeline_name):
return self._jobs.get_definition(pipeline_name)
else:
return self._pipelines.get_definition(pipeline_name)
def get_job(self, job_name: str) -> JobDefinition:
"""Get a job by name.
If this job has not yet been constructed, only this job is constructed, and will
be cached for future calls.
Args:
job_name (str): Name of the job to retrieve.
Returns:
JobDefinition: The job definition corresponding to the given name.
"""
check.str_param(job_name, "job_name")
return self._jobs.get_definition(job_name)
def get_partition_set_names(self) -> List[str]:
"""Get the names of all partition sets in the repository.
Returns:
List[str]
"""
return self._partition_sets.get_definition_names()
def has_partition_set(self, partition_set_name: str) -> bool:
"""Check if a partition set with a given name is present in the repository.
Args:
partition_set_name (str): The name of the partition set.
Returns:
bool
"""
check.str_param(partition_set_name, "partition_set_name")
return self._partition_sets.has_definition(partition_set_name)
def get_all_partition_sets(self) -> List[PartitionSetDefinition]:
"""Return all partition sets in the repository as a list.
Note that this will construct any partition set that has not yet been constructed.
Returns:
List[PartitionSetDefinition]: All partition sets in the repository.
"""
return self._partition_sets.get_all_definitions()
def get_partition_set(self, partition_set_name: str) -> PartitionSetDefinition:
"""Get a partition set by name.
If this partition set has not yet been constructed, only this partition set is constructed,
and will be cached for future calls.
Args:
partition_set_name (str): Name of the partition set to retrieve.
Returns:
PartitionSetDefinition: The partition set definition corresponding to the given name.
"""
check.str_param(partition_set_name, "partition_set_name")
return self._partition_sets.get_definition(partition_set_name)
def get_schedule_names(self) -> List[str]:
"""Get the names of all schedules in the repository.
Returns:
List[str]
"""
return self._schedules.get_definition_names()
def get_all_schedules(self) -> List[ScheduleDefinition]:
"""Return all schedules in the repository as a list.
Note that this will construct any schedule that has not yet been constructed.
Returns:
List[ScheduleDefinition]: All schedules in the repository.
"""
return self._schedules.get_all_definitions()
def get_schedule(self, schedule_name: str) -> ScheduleDefinition:
"""Get a schedule by name.
if this schedule has not yet been constructed, only this schedule is constructed, and will
be cached for future calls.
args:
schedule_name (str): name of the schedule to retrieve.
Returns:
ScheduleDefinition: The schedule definition corresponding to the given name.
"""