-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdora.py
1076 lines (908 loc) · 36.7 KB
/
dora.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
import collections
import collections.abc
import concurrent.futures
import dataclasses
import datetime
import enum
import functools
import http
import logging
import statistics
import typing
import urllib.parse
import aiohttp.web
import cachetools.keys
import dateutil.parser
import github3
import ci.util
import cnudie.iter
import cnudie.iter_async
import cnudie.retrieve_async
import cnudie.util
import ocm
import version as versionutil
import caching
import components
import consts
import util
logger = logging.getLogger(__name__)
changes_by_dependencies_cache = dict()
@dataclasses.dataclass(frozen=True)
class CodeChange:
'''
Represents a code change with its commit data and deployment date
'''
commit_sha: str
commit_date: datetime.datetime
deployment_date: datetime.datetime
@dataclasses.dataclass(frozen=True)
class ComponentDependencyChangeWithCommits:
'''
Holds a Dependency Change for a specific Component as well as the commits included within the
Dependency Change
'''
component: ocm.Component
dependency_component_vector: components.ComponentVector
commits: list[github3.github.repo.commit.ShortCommit]
@dataclasses.dataclass(frozen=True)
class ComponentWithDependencyChanges:
'''
Holds a component descriptor as well as a list of dependency updates, which
where introduced in this component Version
'''
component_descriptor: ocm.ComponentDescriptor
dependency_changes: list[components.ComponentVector]
class CalculationType(enum.StrEnum):
MEDIAN = 'median'
AVERAGE = 'average'
class DeploymentFrequencyBuckets(enum.StrEnum):
'''
Typical Buckets to which a deplyoment Frequency can be assigned
'''
daily = 'daily'
weekly = 'weekly'
monthly = 'monthly'
yearly = 'yearly'
@dataclasses.dataclass(frozen=True)
class DoraDeploymentsResponse:
'''
Helper datacalss for creating JSON response for the DoraMetrics Route
'''
target_deployment_version: str
component_version: str
deployment_date: datetime.datetime
median_change_lead_time: float
changes: list[CodeChange]
@dataclasses.dataclass(frozen=True)
class DoraMonthlyResponse:
'''
Helper datacalss for creating JSON response for the DoraMetrics Route
'''
year: int
month: int
median_change_lead_time: float
changes: list[CodeChange]
@dataclasses.dataclass(frozen=True)
class DoraDependencyResponse:
'''
Helper datacalss for creating JSON response for the DoraMetrics Route
'''
change_lead_time_median: float
change_lead_time_average: float
deployment_frequency: float
changes_monthly: list[DoraMonthlyResponse]
deployments: list[DoraDeploymentsResponse]
all_changes: list[CodeChange]
repo_url: str
@dataclasses.dataclass(frozen=True)
class DoraResponse:
'''
Helper datacalss for creating JSON response for the DoraMetrics Route
'''
change_lead_time_median: float
change_lead_time_average: float
dependencies: dict[str, DoraDependencyResponse]
async def versions_descriptors_newer_than(
component_name: str,
date: datetime.datetime,
component_descriptor_lookup: cnudie.retrieve_async.ComponentDescriptorLookupById,
version_lookup: cnudie.retrieve_async.VersionLookupByComponent,
only_releases: bool = True,
invalid_semver_ok: bool = False,
sorting_direction: typing.Literal['asc', 'desc'] = 'desc'
):
'''
This function retrieves the component descriptors for the versions
of a specific Component, which are newer then the given date.
asc-sorting means old to new => [0.102.0 ... 0.321.2]
desc-sorting means new to old => [0.321.2 ... 0.102.0]
'''
def _filter_component_newer_than_date(
descriptor: ocm.ComponentDescriptor,
date: datetime.datetime,
) -> bool:
creation_date: datetime.datetime = components.get_creation_date(descriptor.component)
return creation_date > date
versions = await all_versions_sorted(
component=component_name,
sorting_direction='desc',
invalid_semver_ok=invalid_semver_ok,
only_releases=only_releases,
version_lookup=version_lookup,
)
descriptors: list[ocm.ComponentDescriptor] = []
for version in versions:
descriptor = await component_descriptor_lookup((component_name, version))
try:
if not _filter_component_newer_than_date(descriptor, date):
break
except KeyError:
continue
descriptors.append(descriptor)
if sorting_direction == 'asc':
descriptors.reverse()
return descriptors
def _cache_key_gen_all_versions_sorted(
component: cnudie.util.ComponentName,
version_lookup: cnudie.retrieve_async.VersionLookupByComponent,
only_releases: bool = True,
invalid_semver_ok: bool = False,
sorting_direction: typing.Literal['asc', 'desc'] = 'desc',
):
return cachetools.keys.hashkey(
cnudie.util.to_component_name(component),
only_releases,
invalid_semver_ok,
sorting_direction,
)
@caching.async_cached(
cache=caching.TTLFilesystemCache(ttl=60 * 60 * 24, max_total_size_mib=128), # 1 day
key_func=_cache_key_gen_all_versions_sorted,
)
async def all_versions_sorted(
component: cnudie.util.ComponentName,
version_lookup: cnudie.retrieve_async.VersionLookupByComponent,
only_releases: bool = True,
invalid_semver_ok: bool = False,
sorting_direction: typing.Literal['asc', 'desc'] = 'desc'
) -> list[str]:
'''
This is a convenience function for looking up all versions of a specific
component.
asc-sorting means old to new => [0.102.0 ... 0.321.2]
desc-sorting means new to old => [0.321.2 ... 0.102.0]
'''
component_name = cnudie.util.to_component_name(component)
def filter_version(version: str, invalid_semver_ok: bool, only_releases:bool):
if not (parsed_version := versionutil.parse_to_semver(
version=version,
invalid_semver_ok=invalid_semver_ok,
)):
return False
if only_releases:
return versionutil.is_final(parsed_version)
return True
versions = (
version for version
in await version_lookup(component_name)
if filter_version(version, invalid_semver_ok, only_releases)
)
versions = sorted(
versions,
key=lambda v: versionutil.parse_to_semver(
version=v,
invalid_semver_ok=invalid_semver_ok,
),
reverse=sorting_direction == 'desc',
)
return versions
async def get_next_older_descriptor(
component_id: ocm.ComponentIdentity,
component_descriptor_lookup: cnudie.retrieve_async.ComponentDescriptorLookupById,
component_version_lookup: cnudie.retrieve_async.VersionLookupByComponent,
) -> ocm.ComponentDescriptor | None:
all_versions = await all_versions_sorted(
component=component_id,
version_lookup=component_version_lookup,
sorting_direction='desc',
)
if (version_index := all_versions.index(component_id.version)) != len(all_versions) - 1:
old_target_version = all_versions[version_index + 1]
else:
return None
return await component_descriptor_lookup(
ocm.ComponentIdentity(
name=component_id.name,
version=old_target_version,
),
)
def next_older_month(date: datetime.datetime) -> datetime.datetime:
month = 12 if date.month == 1 else date.month - 1
year = date.year - 1 if date.month == 1 else date.year
older_month_date = datetime.datetime(year, month, 1, tzinfo=datetime.UTC)
return older_month_date
def can_process(dependency_update: components.ComponentVector):
old_main_source = cnudie.util.main_source(dependency_update.start)
new_main_source = cnudie.util.main_source(dependency_update.end)
if (
not isinstance(old_main_source.access, ocm.GithubAccess)
or not isinstance(new_main_source.access, ocm.GithubAccess)
):
return False
if (
not isinstance(old_main_source.access.commit, str)
or not isinstance(new_main_source.access.commit, str)
):
return False
return True
def _cache_key_gen_component_vector_and_lookup(
left_commit: str,
right_commit: str,
github_repo,
):
return cachetools.keys.hashkey(
left_commit,
right_commit,
)
@caching.cached(
cache=caching.LFUFilesystemCache(max_total_size_mib=256),
key_func=_cache_key_gen_component_vector_and_lookup,
)
def commits_for_component_change(
left_commit: str,
right_commit: str,
github_repo: github3.repos.Repository,
) -> tuple[github3.github.repo.commit.ShortCommit]:
'''
returns commits between passed-on commits. results are read from github-api and cached.
passed-on commits must exist in repository referenced by passed-in github_repo.
'''
return tuple(github_repo.compare_commits(
left_commit,
right_commit,
).commits())
def _cache_key_changes_by_dependencies(
target_descriptors_with_updates: tuple[ComponentWithDependencyChanges],
):
return cachetools.keys.hashkey(''.join([(
f'{target_descriptor_with_updates.component_descriptor.component.name}'
f'{target_descriptor_with_updates.component_descriptor.component.version}'
) for target_descriptor_with_updates in target_descriptors_with_updates]))
def categorize_by_changed_component(
target_descriptors_with_updates: tuple[ComponentWithDependencyChanges],
github_api_lookup,
) -> dict[str, list[ComponentDependencyChangeWithCommits]]:
dependencies: dict[str, list[ComponentDependencyChangeWithCommits]] = (
collections.defaultdict(list[ComponentDependencyChangeWithCommits])
)
_github_api = functools.cache(github_api_lookup)
@functools.cache
def _github_repo(repo_url: urllib.parse.ParseResult):
github = _github_api(repo_url)
org, repo = repo_url.path.strip('/').split('/')
return github.repository(org, repo)
def resolve_changes(
target_descriptor_with_updates: ComponentWithDependencyChanges,
):
for dependency_update in target_descriptor_with_updates.dependency_changes:
target_component = target_descriptor_with_updates.component_descriptor.component
dependency_component_name = dependency_update.end.name
left_component = dependency_update.start
right_component = dependency_update.end
left_src = cnudie.util.main_source(
left_component,
absent_ok=True,
)
right_src = cnudie.util.main_source(
right_component,
absent_ok=True,
)
if not left_src or not right_src:
continue
left_access = left_src.access
right_access = right_src.access
if not left_access.type is ocm.AccessType.GITHUB:
continue
if not right_access.type is ocm.AccessType.GITHUB:
continue
left_repo_url = ci.util.urlparse(left_access.repoUrl)
right_repo_url = ci.util.urlparse(right_access.repoUrl)
if not left_repo_url == right_repo_url:
continue # ensure there was no repository-change between component-versions
left_commit = left_access.commit or left_access.ref
right_commit = right_access.commit or right_access.ref
github_repo = _github_repo(
repo_url=left_repo_url, # already checked for equality; choose either
)
dependencies[dependency_component_name].append(
ComponentDependencyChangeWithCommits(
component=target_component,
dependency_component_vector=dependency_update,
commits=commits_for_component_change(
left_commit=left_commit,
right_commit=right_commit,
github_repo=github_repo,
),
)
)
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as tpe:
futures = {
tpe.submit(resolve_changes, target_descriptor_with_updates)
for target_descriptor_with_updates in target_descriptors_with_updates
}
concurrent.futures.wait(futures)
key = _cache_key_changes_by_dependencies(target_descriptors_with_updates)
changes_by_dependencies_cache[key] = dependencies
return dependencies
def _cache_key_gen_dora(
component_dependency_changes_with_commits: list[
ComponentDependencyChangeWithCommits
],
time_span_days: int | None = None,
calculation_type: CalculationType | None = None
):
component_versions = tuple(
component_dependency_change_with_commits.component.version
for component_dependency_change_with_commits in component_dependency_changes_with_commits
)
hashkey_elements = (
component_dependency_changes_with_commits[0].component.name,
component_dependency_changes_with_commits[0].dependency_component_vector.start.name,
component_dependency_changes_with_commits[0].dependency_component_vector.end.name,
component_dependency_changes_with_commits[0].dependency_component_vector.start.version,
component_dependency_changes_with_commits[0].dependency_component_vector.end.version,
component_versions,
)
if time_span_days: hashkey_elements += (time_span_days, datetime.date.today())
if calculation_type: hashkey_elements += (calculation_type,)
return cachetools.keys.hashkey(*hashkey_elements)
@caching.cached(
cache=caching.LFUFilesystemCache(max_total_size_mib=128),
key_func=_cache_key_gen_dora,
)
def calculate_change_lead_time(
component_dependency_changes_with_commits: list[
ComponentDependencyChangeWithCommits
],
time_span_days: int,
calculation_type: CalculationType,
) -> datetime.timedelta:
time_differences: list[datetime.timedelta] = []
for component_dependency_change_with_commits in component_dependency_changes_with_commits:
deployment_date = components.get_creation_date(
component_dependency_change_with_commits.component
)
for commit in component_dependency_change_with_commits.commits:
if (
(
commit_date := dateutil.parser.isoparse(commit.commit.author['date'])
) > (
datetime.datetime.now(datetime.timezone.utc)
- datetime.timedelta(days=time_span_days)
)
):
time_differences.append(deployment_date - commit_date)
if not time_differences:
time_differences.append(datetime.timedelta(seconds=-1))
if calculation_type is CalculationType.MEDIAN:
result_in_seconds: float = statistics.median(
[time_difference.total_seconds()
for time_difference in time_differences]
)
else:
result_in_seconds: float = statistics.mean(
[time_difference.total_seconds()
for time_difference in time_differences]
)
return datetime.timedelta(seconds=result_in_seconds)
@caching.cached(
cache=caching.LFUFilesystemCache(max_total_size_mib=128),
key_func=_cache_key_gen_dora,
)
def dora_changes_monthly(
component_dependency_changes_with_commits: list[
ComponentDependencyChangeWithCommits
],
time_span_days: int,
) -> list[DoraMonthlyResponse]:
code_changes_by_month: dict[
tuple[int, int],
list[tuple[datetime.datetime, CodeChange]],
] = (
collections.defaultdict(list[tuple[datetime.datetime, CodeChange]])
)
for component_dependency_change_with_commits in component_dependency_changes_with_commits:
for commit in component_dependency_change_with_commits.commits:
if (
(
commit_date := dateutil.parser.isoparse(commit.commit.author['date'])
) > (
datetime.datetime.now(datetime.timezone.utc) -
datetime.timedelta(days=time_span_days)
)
):
commit_sha: str = commit.sha
key = (commit_date.year, commit_date.month)
code_changes_by_month[key].append(
(
components.get_creation_date(
component_dependency_change_with_commits.component
),
CodeChange(
commit_date=commit_date,
commit_sha=commit_sha,
deployment_date=components.get_creation_date(
component_dependency_change_with_commits.component
),
),
),
)
by_month_list: list[DoraMonthlyResponse] = []
for (year, month), code_changes in code_changes_by_month.items():
median_change_lead_time = datetime.timedelta(seconds=statistics.median(
[
(deploy_date - commits_and_date.commit_date).total_seconds()
for deploy_date, commits_and_date in code_changes
]
))
by_month_list.append(DoraMonthlyResponse(
changes=[commits_and_date for _, commits_and_date in code_changes],
month=month,
year=year,
median_change_lead_time=median_change_lead_time.days,
))
# create "empty" months which lie within the time_span_days
entry_date = (
datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=time_span_days)
)
while entry_date < datetime.datetime.now(datetime.timezone.utc):
if (entry_date.year, entry_date.month) not in code_changes_by_month:
by_month_list.append(DoraMonthlyResponse(
changes=[],
month=entry_date.month,
year=entry_date.year,
median_change_lead_time=-1,
))
entry_date += datetime.timedelta(days=30)
return by_month_list
@caching.cached(
cache=caching.LFUFilesystemCache(max_total_size_mib=128),
key_func=_cache_key_gen_dora,
)
def dora_deployments(
component_dependency_changes_with_commits: list[
ComponentDependencyChangeWithCommits
],
) -> list[DoraDeploymentsResponse]:
deployments: list[DoraDeploymentsResponse] = []
for component_dependency_change_with_commits in component_dependency_changes_with_commits:
median_change_lead_time = datetime.timedelta(
seconds=statistics.median([
(components.get_creation_date(
component_dependency_change_with_commits.component
) - dateutil.parser.isoparse(
commit.commit.author['date']
)).total_seconds()
for commit in component_dependency_change_with_commits.commits
]) if component_dependency_change_with_commits.commits else 0,
)
deployment_date = components.get_creation_date(
component_dependency_change_with_commits.component
)
deployments.append(
DoraDeploymentsResponse(
deployment_date=deployment_date,
component_version=(
component_dependency_change_with_commits.dependency_component_vector.end.version
),
target_deployment_version=component_dependency_change_with_commits.component.version,
changes=[
CodeChange(
commit_date=dateutil.parser.isoparse(commit.commit.author['date']),
commit_sha=commit.sha,
deployment_date=deployment_date,
)
for commit in component_dependency_change_with_commits.commits
],
median_change_lead_time=median_change_lead_time.days,
)
)
return deployments
def all_change_lead_time_durations(
component_dependency_changes_with_commits: list[
ComponentDependencyChangeWithCommits
],
time_span_days: int,
) -> list[int]:
commit_durations = []
for component_dependency_change_with_commits in component_dependency_changes_with_commits:
commit_durations.extend(
[
(
components.get_creation_date(
component_dependency_change_with_commits.component
)
- dateutil.parser.isoparse(commit.commit.author['date'])
).total_seconds()
for commit in component_dependency_change_with_commits.commits
if (
dateutil.parser.isoparse(commit.commit.author['date']) >
(
datetime.datetime.now(datetime.timezone.utc)
- datetime.timedelta(days=time_span_days)
)
)
]
)
return commit_durations
def all_changes(
component_dependency_changes_with_commits: list[
ComponentDependencyChangeWithCommits
],
time_span_days: int,
) -> list[CodeChange]:
all_changes = []
for component_dependency_change_with_commits in component_dependency_changes_with_commits:
all_changes.extend(
[
CodeChange(
commit_sha=commit.sha,
commit_date=dateutil.parser.isoparse(commit.commit.author['date']),
deployment_date=components.get_creation_date(
component_dependency_change_with_commits.component,
),
) for commit in component_dependency_change_with_commits.commits
if dateutil.parser.isoparse(commit.commit.author['date']) >
datetime.datetime.now(datetime.UTC) - datetime.timedelta(days=time_span_days)
]
)
return all_changes
def create_response_object(
target_updates_by_dependency: dict[
str,
list[ComponentDependencyChangeWithCommits],
],
time_span_days: int,
):
dependencies_response: dict[
str,
DoraDependencyResponse,
] = {}
all_change_lead_time_durations_seconds = []
for dependency_name, component_dependency_changes_with_commits \
in target_updates_by_dependency.items():
median = calculate_change_lead_time(
component_dependency_changes_with_commits,
time_span_days,
CalculationType.MEDIAN,
)
average = calculate_change_lead_time(
component_dependency_changes_with_commits,
time_span_days,
CalculationType.AVERAGE,
)
changes_monthly = dora_changes_monthly(
component_dependency_changes_with_commits,
time_span_days,
)
deployments = dora_deployments(
component_dependency_changes_with_commits,
)
changes = all_changes(
component_dependency_changes_with_commits,
time_span_days,
)
repo_url = cnudie.util.main_source(
component_dependency_changes_with_commits[0].dependency_component_vector.start
).access.repoUrl
dependencies_response[dependency_name] = DoraDependencyResponse(
change_lead_time_median=median.days,
change_lead_time_average=average.days,
deployment_frequency=round(time_span_days / len(deployments), 2),
changes_monthly=changes_monthly,
deployments=deployments,
all_changes=changes,
repo_url=repo_url,
)
all_change_lead_time_durations_seconds.extend(
all_change_lead_time_durations(
component_dependency_changes_with_commits,
time_span_days,
)
)
if all_change_lead_time_durations_seconds != []:
change_lead_time_median = datetime.timedelta(
seconds=statistics.median(
all_change_lead_time_durations_seconds
)
).days
change_lead_time_average = datetime.timedelta(
seconds=statistics.mean(
all_change_lead_time_durations_seconds
)
).days
else:
change_lead_time_median = -1
change_lead_time_average = -1
return DoraResponse(
change_lead_time_median=change_lead_time_median,
change_lead_time_average=change_lead_time_average,
dependencies=dependencies_response,
)
class DoraMetrics(aiohttp.web.View):
async def get(self):
'''
---
tags:
- Dora
produces:
- application/json
parameters:
- in: query
name: target_component_name
type: string
required: true
- in: query
name: time_span_days
type: integer
required: false
default: 90
- in: query
name: filter_component_names
schema:
type: array
items:
type: string
required: false
responses:
"200":
description: Successful operation.
schema:
type: object
required:
- change_lead_time_median
- change_lead_time_average
- dependencies
properties:
change_lead_time_median:
type: number
change_lead_time_average:
type: number
dependencies:
type: object
"202":
description: Dora metric calculation pending, client should retry.
'''
params = self.request.rel_url.query
target_component_name = util.param(params, 'target_component_name', required=True)
time_span_days = int(util.param(params, 'time_span_days', default=90))
filter_component_names = params.getall('filter_component_names', default=[])
component_descriptor_lookup = self.request.app[consts.APP_COMPONENT_DESCRIPTOR_LOOKUP]
version_lookup = self.request.app[consts.APP_VERSION_LOOKUP]
await components.check_if_component_exists(
component_name=target_component_name,
version_lookup=version_lookup,
raise_http_error=True,
)
for filter_component_name in filter_component_names:
await components.check_if_component_exists(
component_name=filter_component_name,
version_lookup=version_lookup,
raise_http_error=True,
)
# get all component descriptors of component versions of target component within time span
target_descriptors_in_time_span = await versions_descriptors_newer_than(
component_name=target_component_name,
date=datetime.datetime.now(datetime.UTC) - datetime.timedelta(days=time_span_days),
component_descriptor_lookup=component_descriptor_lookup,
version_lookup=version_lookup,
sorting_direction='asc',
)
# Add the next older version, which is not within the time span anymore (if one exists)
# at the beginning of the descriptor list to be able to detect changes which were
# first introduced within the time span of the target component version.
if (next_older_descriptor := await get_next_older_descriptor(
component_id=ocm.ComponentIdentity(
target_component_name,
target_descriptors_in_time_span[0].component.version,
),
component_descriptor_lookup=component_descriptor_lookup,
component_version_lookup=version_lookup,
)):
target_descriptors_in_time_span.insert(0, next_older_descriptor)
# calculate the changes which where introduced for every component version
target_descriptors_with_updates: list[ComponentWithDependencyChanges] = []
for index in range(1, len(target_descriptors_in_time_span)):
component_diff = await _diff_components(
component_vector=components.ComponentVector(
start=target_descriptors_in_time_span[index-1].component,
end=target_descriptors_in_time_span[index].component,
),
component_descriptor_lookup=component_descriptor_lookup,
)
if component_diff:
dependency_changes = dependency_changes_between_versions(
component_diff=component_diff,
dependency_name_filter=filter_component_names,
only_rising_changes=True,
)
else:
dependency_changes = []
target_descriptors_with_updates.append(
ComponentWithDependencyChanges(
component_descriptor=target_descriptors_in_time_span[index],
dependency_changes=dependency_changes,
)
)
target_descriptors_with_updates = tuple(target_descriptors_with_updates)
key = _cache_key_changes_by_dependencies(target_descriptors_with_updates)
# categorize changes by changed dependency
# and add commits to the dependency changes
if (updates_by_dependency := changes_by_dependencies_cache.get(key)) is None:
if key not in changes_by_dependencies_cache:
changes_by_dependencies_cache[key] = None
tpe = concurrent.futures.ThreadPoolExecutor(max_workers=1)
tpe.submit(
categorize_by_changed_component,
target_descriptors_with_updates,
self.request.app[consts.APP_GITHUB_API_LOOKUP],
)
return aiohttp.web.Response(
status=http.HTTPStatus.ACCEPTED,
)
return aiohttp.web.json_response(
data=create_response_object(
target_updates_by_dependency=updates_by_dependency,
time_span_days=time_span_days,
),
dumps=util.dict_to_json_factory,
)
def _cache_key_diff_components(
component_vector: components.ComponentVector,
component_descriptor_lookup: cnudie.retrieve_async.ComponentDescriptorLookupById,
):
return cachetools.keys.hashkey(
component_vector.start.name,
component_vector.end.name,
component_vector.start.version,
component_vector.end.version,
)
@caching.async_cached(
cache=caching.LFUFilesystemCache(max_total_size_mib=256),
key_func=_cache_key_diff_components,
)
async def _diff_components(
component_vector: components.ComponentVector,
component_descriptor_lookup: cnudie.retrieve_async.ComponentDescriptorLookupById,
) -> cnudie.util.ComponentDiff | None:
'''
calculates component-diff between components from passed-in component-vector
this function is mostly identical to cnudie.util.diff_components. It differs, however,
in that it will merge multiple component-versions (of the same component) into just one
component-version, choosing greatest/smallest versions.
'''
old_components = [
c.component async for c in cnudie.iter_async.iter(
component=component_vector.start,
lookup=component_descriptor_lookup,
node_filter=cnudie.iter.Filter.components,
)
]
new_components = [
c.component async for c in cnudie.iter_async.iter(
component=component_vector.end,
lookup=component_descriptor_lookup,
node_filter=cnudie.iter.Filter.components,
)
]
def only_greatest_versions(components: list[ocm.Component]):
components_by_name: collections.defaultdict[
str, list[ocm.Component]
] = collections.defaultdict(list[ocm.Component])
for c in components:
components_by_name[c.name].append(c)
greatest_component_versions = []
for component_name, component_list in components_by_name.items():
if len(component_list) == 1:
greatest_component_versions.append(component_list[0])
continue
current_biggest_version = component_list[0]
for c in component_list[1:]:
if(
versionutil.parse_to_semver(c.version) >
versionutil.parse_to_semver(current_biggest_version.version)
):
current_biggest_version = c
greatest_component_versions.append(current_biggest_version)
return greatest_component_versions
old_greatest_component_versions = only_greatest_versions(old_components)
new_greatest_component_versions = only_greatest_versions(new_components)
old_greatest_component_identities = {
c.identity() for c in old_greatest_component_versions
}
new_greatest_component_identities = {
c.identity() for c in new_greatest_component_versions
}
old_only_greatest_component_identities = (
old_greatest_component_identities - new_greatest_component_identities
)
new_only_greatest_component_identities = (
new_greatest_component_identities - old_greatest_component_identities
)
old_only_greatest_component_versions = [
c for c in old_greatest_component_versions
if c.identity() in old_only_greatest_component_identities
]
new_only_greatest_component_versions = [
c for c in new_greatest_component_versions
if c.identity() in new_only_greatest_component_identities
]
if old_only_greatest_component_identities == new_only_greatest_component_identities:
return None # no diff
def find_changed_component(
old_only_component_version: ocm.Component,
new_only_component_versions: list[ocm.Component],
):
for new_only_component_version in new_only_component_versions: