/
NodeState.java
1355 lines (1222 loc) · 59.9 KB
/
NodeState.java
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 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.builder;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import org.apache.commons.lang.StringUtils;
import org.gradle.api.Action;
import org.gradle.api.artifacts.ModuleIdentifier;
import org.gradle.api.artifacts.component.ComponentSelector;
import org.gradle.api.artifacts.component.ModuleComponentIdentifier;
import org.gradle.api.artifacts.component.ModuleComponentSelector;
import org.gradle.api.artifacts.result.ResolvedVariantResult;
import org.gradle.api.attributes.AttributeContainer;
import org.gradle.api.capabilities.Capability;
import org.gradle.api.internal.artifacts.DependencySubstitutionInternal;
import org.gradle.api.internal.artifacts.ResolvedConfigurationIdentifier;
import org.gradle.api.internal.artifacts.ivyservice.dependencysubstitution.ArtifactSelectionDetailsInternal;
import org.gradle.api.internal.artifacts.ivyservice.dependencysubstitution.DependencySubstitutionApplicator;
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.excludes.ModuleExclusions;
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.excludes.specs.ExcludeSpec;
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.DependencyGraphNode;
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.conflicts.CapabilitiesConflictHandler;
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.strict.StrictVersionConstraints;
import org.gradle.api.internal.artifacts.result.DefaultResolvedVariantResult;
import org.gradle.api.internal.attributes.AttributesSchemaInternal;
import org.gradle.api.internal.attributes.ImmutableAttributes;
import org.gradle.api.internal.attributes.ImmutableAttributesFactory;
import org.gradle.internal.Describables;
import org.gradle.internal.DisplayName;
import org.gradle.internal.component.external.model.DefaultModuleComponentSelector;
import org.gradle.internal.component.external.model.ShadowedCapability;
import org.gradle.internal.component.external.model.VirtualComponentIdentifier;
import org.gradle.internal.component.local.model.LocalConfigurationMetadata;
import org.gradle.internal.component.local.model.LocalFileDependencyMetadata;
import org.gradle.internal.component.model.ComponentResolveMetadata;
import org.gradle.internal.component.model.ConfigurationMetadata;
import org.gradle.internal.component.model.DependencyMetadata;
import org.gradle.internal.component.model.ExcludeMetadata;
import org.gradle.internal.component.model.IvyArtifactName;
import org.gradle.internal.component.model.SelectedByVariantMatchingConfigurationMetadata;
import org.gradle.internal.resolve.ModuleVersionResolveException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Represents a node in the dependency graph.
*/
public class NodeState implements DependencyGraphNode {
private static final Logger LOGGER = LoggerFactory.getLogger(NodeState.class);
private final Long resultId;
private final ComponentState component;
private final List<EdgeState> incomingEdges = Lists.newArrayList();
private final List<EdgeState> outgoingEdges = Lists.newArrayList();
private final ResolvedConfigurationIdentifier id;
private final ConfigurationMetadata metaData;
private final ResolveState resolveState;
private final ModuleExclusions moduleExclusions;
private final boolean isTransitive;
private final boolean selectedByVariantAwareResolution;
private final boolean dependenciesMayChange;
private boolean doesNotHaveDependencies;
@Nullable
ExcludeSpec previousTraversalExclusions;
// In opposite to outgoing edges, virtual edges are for now pretty rare, so they are created lazily
private List<EdgeState> virtualEdges;
private boolean queued;
private boolean evicted;
private int transitiveEdgeCount;
private Set<ModuleIdentifier> upcomingNoLongerPendingConstraints;
private boolean virtualPlatformNeedsRefresh;
private Set<EdgeState> edgesToRecompute;
private Multimap<ModuleIdentifier, DependencyState> potentiallyActivatedConstraints;
// caches
private final Map<DependencyMetadata, DependencyState> dependencyStateCache = Maps.newHashMap();
private final Map<DependencyState, EdgeState> edgesCache = Maps.newHashMap();
// Caches the list of dependency states for dependencies
private List<DependencyState> cachedDependencyStates;
// Caches the list of dependency states which are NOT excluded
private List<DependencyState> cachedFilteredDependencyStates;
// exclusions optimizations
private ExcludeSpec cachedNodeExclusions;
private int previousIncomingEdgeCount;
private long previousIncomingHash;
private long incomingHash;
private ExcludeSpec cachedModuleResolutionFilter;
private ResolvedVariantResult cachedVariantResult;
private StrictVersionConstraints ancestorsStrictVersionConstraints;
private StrictVersionConstraints ownStrictVersionConstraints;
private List<EdgeState> endorsesStrictVersionsFrom;
private boolean removingOutgoingEdges;
public NodeState(Long resultId, ResolvedConfigurationIdentifier id, ComponentState component, ResolveState resolveState, ConfigurationMetadata md) {
this.resultId = resultId;
this.id = id;
this.component = component;
this.resolveState = resolveState;
this.metaData = md;
this.isTransitive = metaData.isTransitive() || metaData.isExternalVariant();
this.selectedByVariantAwareResolution = md instanceof SelectedByVariantMatchingConfigurationMetadata;
this.moduleExclusions = resolveState == null ? null : resolveState.getModuleExclusions(); // can be null in tests, ResolveState cannot be mocked
this.dependenciesMayChange = component.getModule() != null && component.getModule().isVirtualPlatform(); // can be null in tests, ComponentState cannot be mocked
component.addConfiguration(this);
}
// the enqueue and dequeue methods are used for performance reasons
// in order to avoid tracking the set of enqueued nodes
boolean enqueue() {
if (queued) {
return false;
}
queued = true;
return true;
}
NodeState dequeue() {
queued = false;
return this;
}
@Override
public ComponentState getComponent() {
return component;
}
@Override
public Long getNodeId() {
return resultId;
}
@Override
public boolean isRoot() {
return false;
}
@Override
public ResolvedConfigurationIdentifier getResolvedConfigurationId() {
return id;
}
@Override
public ComponentState getOwner() {
return component;
}
@Override
public List<EdgeState> getIncomingEdges() {
return incomingEdges;
}
@Override
public List<EdgeState> getOutgoingEdges() {
return outgoingEdges;
}
@Override
public ConfigurationMetadata getMetadata() {
return metaData;
}
@Override
public Set<? extends LocalFileDependencyMetadata> getOutgoingFileEdges() {
if (metaData instanceof LocalConfigurationMetadata) {
// Only when this node has a transitive incoming edge
for (EdgeState incomingEdge : incomingEdges) {
if (incomingEdge.isTransitive()) {
return ((LocalConfigurationMetadata) metaData).getFiles();
}
}
}
return Collections.emptySet();
}
@Override
public String toString() {
return String.format("%s(%s)", component, id.getConfiguration());
}
public String getSimpleName() {
return component.getId().toString();
}
public String getNameWithVariant() {
return component.getId() + " variant " + id.getConfiguration();
}
public boolean isTransitive() {
return isTransitive;
}
/**
* Visits all of the dependencies that originate on this node, adding them as outgoing edges.
* The {@link #outgoingEdges} collection is populated, as is the `discoveredEdges` parameter.
*
* @param discoveredEdges A collector for visited edges.
*/
public void visitOutgoingDependencies(Collection<EdgeState> discoveredEdges) {
// If this configuration's version is in conflict, do not traverse.
// If none of the incoming edges are transitive, remove previous state and do not traverse.
// If not traversed before, simply add all selected outgoing edges (either hard or pending edges)
// If traversed before:
// If net exclusions for this node have not changed, ignore
// If net exclusions for this node not changed, remove previous state and traverse outgoing edges again.
if (!component.isSelected()) {
LOGGER.debug("version for {} is not selected. ignoring.", this);
cleanupConstraints();
return;
}
// Check if there are any transitive incoming edges at all. Don't traverse if not.
if (transitiveEdgeCount == 0 && !isRoot() && canIgnoreExternalVariant()) {
handleNonTransitiveNode(discoveredEdges);
return;
}
// Determine the net exclusion for this node, by inspecting all transitive incoming edges
ExcludeSpec resolutionFilter = computeModuleResolutionFilter(incomingEdges);
// Virtual platforms require their constraints to be recomputed each time as each module addition can cause a shift in versions
if (!isVirtualPlatformNeedsRefresh()) {
// Check if node was previously traversed with the same net exclusion when not a virtual platform
if (excludesSameDependenciesAsPreviousTraversal(resolutionFilter)) {
boolean newConstraints = handleNewConstraints(discoveredEdges);
boolean edgesToRecompute = handleEdgesToRecompute(discoveredEdges);
if (!newConstraints && !edgesToRecompute) {
// Was previously traversed, and no change to the set of modules that are linked by outgoing edges.
// Don't need to traverse again, but hang on to the new filter since it may change the set of excluded artifacts.
LOGGER.debug("Changed edges for {} selects same versions as previous traversal. ignoring", this);
}
previousTraversalExclusions = resolutionFilter;
return;
}
}
// Clear previous traversal state, if any
if (previousTraversalExclusions != null) {
removeOutgoingEdges();
upcomingNoLongerPendingConstraints = null;
edgesToRecompute = null;
potentiallyActivatedConstraints = null;
ownStrictVersionConstraints = null;
}
visitDependencies(resolutionFilter, discoveredEdges);
visitOwners(discoveredEdges);
}
private boolean canIgnoreExternalVariant() {
if (!metaData.isExternalVariant()) {
return true;
}
// We need to ignore external variants when all edges are artifact ones
for (EdgeState incomingEdge : incomingEdges) {
if (!incomingEdge.isArtifactOnlyEdge()) {
return false;
}
}
return true;
}
/*
* When a node exits the graph, its constraints need to be cleaned up.
* This means:
* * Rescheduling any deferred selection impacted by a constraint coming from this node
* * Making sure we no longer are registered as pending interest on nodes pointed by constraints
*/
private void cleanupConstraints() {
// This part covers constraint that were taken into account between a selection being deferred and this node being scheduled for traversal
if (upcomingNoLongerPendingConstraints != null) {
for (ModuleIdentifier identifier : upcomingNoLongerPendingConstraints) {
ModuleResolveState module = resolveState.getModule(identifier);
for (EdgeState unattachedDependency : module.getUnattachedDependencies()) {
if (!unattachedDependency.getSelector().isResolved()) {
// Unresolved - we have a selector that was deferred but the constraint has been removed in between
NodeState from = unattachedDependency.getFrom();
from.prepareToRecomputeEdge(unattachedDependency);
}
}
}
upcomingNoLongerPendingConstraints = null;
}
// This part covers constraint that might be triggered in the future if the node they point gains a real edge
if (cachedFilteredDependencyStates != null && !cachedFilteredDependencyStates.isEmpty()) {
// We may have registered this node as pending if it had constraints.
// Let's clear that state since it is no longer part of selection
for (DependencyState dependencyState : cachedFilteredDependencyStates) {
if (dependencyState.getDependency().isConstraint()) {
ModuleResolveState targetModule = resolveState.getModule(dependencyState.getModuleIdentifier());
if (targetModule.isPending()) {
targetModule.unregisterConstraintProvider(this);
}
}
}
}
}
private boolean excludesSameDependenciesAsPreviousTraversal(ExcludeSpec newResolutionFilter) {
List<DependencyState> oldStates = cachedFilteredDependencyStates;
if (previousTraversalExclusions == null || oldStates == null) {
return false;
}
if (previousTraversalExclusions.equals(newResolutionFilter)) {
return true;
}
if (doesNotHaveDependencies && !dependenciesMayChange) {
// whatever the exclude filter, there are no dependencies
return true;
}
cachedFilteredDependencyStates = null;
// here, we need to check that applying the new resolution filter
// we would actually exclude exactly the same dependencies as in
// the previous visit. It is important that this is NOT a heuristic
// (it used to be) because if the filters are _equivalent_, we would
// revisit all dependencies and possibly change the classpath order!
boolean sameDependencies = dependencies(newResolutionFilter).equals(oldStates);
if (sameDependencies) {
// While there will be no change to this node, there might be changes to the nodes it brings as the exclude change could concern them
for (EdgeState outgoingEdge : outgoingEdges) {
outgoingEdge.updateTransitiveExcludes(newResolutionFilter);
}
}
if (LOGGER.isDebugEnabled()) {
if (sameDependencies) {
LOGGER.debug("Filter {} excludes same dependencies as previous {}. Dependencies left = {}", newResolutionFilter, previousTraversalExclusions, oldStates);
} else {
LOGGER.debug("Filter {} doesn't exclude same dependencies as previous {}. Previous dependencies left = {} - New dependencies left = {}", newResolutionFilter, previousTraversalExclusions, oldStates, cachedFilteredDependencyStates);
}
}
return sameDependencies;
}
private void prepareToRecomputeEdge(EdgeState edgeToRecompute) {
if (edgesToRecompute == null) {
edgesToRecompute = Sets.newLinkedHashSet();
}
edgesToRecompute.add(edgeToRecompute);
resolveState.onMoreSelected(this);
}
private boolean handleEdgesToRecompute(Collection<EdgeState> discoveredEdges) {
if (edgesToRecompute != null) {
discoveredEdges.addAll(edgesToRecompute);
edgesToRecompute = null;
return true;
}
return false;
}
private boolean handleNewConstraints(Collection<EdgeState> discoveredEdges) {
if (upcomingNoLongerPendingConstraints != null) {
// Previously traversed but new constraints no longer pending, so partial traversing
visitAdditionalConstraints(discoveredEdges);
return true;
}
return false;
}
private boolean isVirtualPlatformNeedsRefresh() {
return virtualPlatformNeedsRefresh;
}
/**
* Removes outgoing edges from no longer transitive node
* Also process {@code belongsTo} if node still has edges at all.
*
* @param discoveredEdges In/Out parameter collecting dependencies or platforms
*/
private void handleNonTransitiveNode(Collection<EdgeState> discoveredEdges) {
cleanupConstraints();
// If node was previously traversed, need to remove outgoing edges.
if (previousTraversalExclusions != null) {
removeOutgoingEdges();
}
if (!incomingEdges.isEmpty()) {
LOGGER.debug("{} has no transitive incoming edges. ignoring outgoing edges.", this);
visitOwners(discoveredEdges);
} else {
LOGGER.debug("{} has no incoming edges. ignoring.", this);
}
}
private DependencyState createDependencyState(DependencyMetadata md) {
return new DependencyState(md, resolveState.getComponentSelectorConverter());
}
/**
* Iterate over the dependencies originating in this node, adding them either as a 'pending' dependency
* or adding them to the `discoveredEdges` collection (and `this.outgoingEdges`)
*/
private void visitDependencies(ExcludeSpec resolutionFilter, Collection<EdgeState> discoveredEdges) {
PendingDependenciesVisitor pendingDepsVisitor = resolveState.newPendingDependenciesVisitor();
Set<ModuleIdentifier> strictVersionsSet = null;
boolean shouldComputeOwnStrictVersions = ownStrictVersionConstraints == null;
try {
collectAncestorsStrictVersions(incomingEdges);
for (DependencyState dependencyState : dependencies(resolutionFilter)) {
PendingDependenciesVisitor.PendingState pendingState = pendingDepsVisitor.maybeAddAsPendingDependency(this, dependencyState);
if (dependencyState.getDependency().isConstraint()) {
registerActivatingConstraint(dependencyState);
}
if (!pendingState.isPending()) {
createAndLinkEdgeState(dependencyState, discoveredEdges, resolutionFilter, pendingState == PendingDependenciesVisitor.PendingState.NOT_PENDING_ACTIVATING);
}
if (shouldComputeOwnStrictVersions) {
strictVersionsSet = maybeCollectStrictVersions(strictVersionsSet, dependencyState);
}
}
previousTraversalExclusions = resolutionFilter;
} finally {
// If there are 'pending' dependencies that share a target with any of these outgoing edges,
// then reset the state of the node that owns those dependencies.
// This way, all edges of the node will be re-processed.
pendingDepsVisitor.complete();
if (shouldComputeOwnStrictVersions) {
storeOwnStrictVersions(strictVersionsSet);
}
}
}
private void registerActivatingConstraint(DependencyState dependencyState) {
if (potentiallyActivatedConstraints == null) {
potentiallyActivatedConstraints = LinkedHashMultimap.create();
}
potentiallyActivatedConstraints.put(dependencyState.getModuleIdentifier(), dependencyState);
}
private List<? extends DependencyMetadata> dependencies() {
if (dependenciesMayChange) {
cachedDependencyStates = null;
cachedFilteredDependencyStates = null;
}
List<? extends DependencyMetadata> dependencies = getAllDependencies();
if (transitiveEdgeCount == 0 && metaData.isExternalVariant()) {
// there must be a single dependency state because this variant is an "available-at"
// variant and here we are in the case the "including" component said that transitive
// should be false so we need to arbitrarily carry that onto the dependency metadata
assert dependencies.size() == 1;
dependencies = Collections.singletonList(makeNonTransitive(dependencies.get(0)));
}
doesNotHaveDependencies = dependencies.isEmpty();
return dependencies;
}
protected List<? extends DependencyMetadata> getAllDependencies() {
return metaData.getDependencies();
}
private static DependencyMetadata makeNonTransitive(DependencyMetadata dependencyMetadata) {
return new NonTransitiveVariantDependencyMetadata(dependencyMetadata);
}
private List<DependencyState> dependencies(ExcludeSpec spec) {
List<? extends DependencyMetadata> dependencies = dependencies();
if (cachedDependencyStates == null) {
cachedDependencyStates = cacheDependencyStates(dependencies);
}
if (cachedFilteredDependencyStates == null) {
cachedFilteredDependencyStates = cacheFilteredDependencyStates(spec, cachedDependencyStates);
}
return cachedFilteredDependencyStates;
}
private List<DependencyState> cacheFilteredDependencyStates(ExcludeSpec spec, List<DependencyState> from) {
if (from.isEmpty()) {
return from;
}
List<DependencyState> tmp = Lists.newArrayListWithCapacity(from.size());
for (DependencyState dependencyState : from) {
if (isExcluded(spec, dependencyState)) {
continue;
}
dependencyState = maybeSubstitute(dependencyState, resolveState.getDependencySubstitutionApplicator());
if (!isExcluded(spec, dependencyState)) {
tmp.add(dependencyState);
}
}
return tmp;
}
private List<DependencyState> cacheDependencyStates(List<? extends DependencyMetadata> dependencies) {
if (dependencies.isEmpty()) {
return Collections.emptyList();
}
List<DependencyState> tmp = Lists.newArrayListWithCapacity(dependencies.size());
for (DependencyMetadata dependency : dependencies) {
tmp.add(cachedDependencyStateFor(dependency));
}
return tmp;
}
private DependencyState cachedDependencyStateFor(DependencyMetadata md) {
return dependencyStateCache.computeIfAbsent(md, this::createDependencyState);
}
private void createAndLinkEdgeState(DependencyState dependencyState, Collection<EdgeState> discoveredEdges, ExcludeSpec resolutionFilter, boolean deferSelection) {
EdgeState dependencyEdge = edgesCache.computeIfAbsent(dependencyState, ds -> new EdgeState(this, ds, resolutionFilter, resolveState));
dependencyEdge.computeSelector(); // the selector changes, if the 'versionProvidedByAncestors' state changes
outgoingEdges.add(dependencyEdge);
dependencyEdge.markUsed();
discoveredEdges.add(dependencyEdge);
dependencyEdge.getSelector().use(deferSelection);
}
/**
* Iterate over the dependencies originating in this node, adding only the constraints listed
* in upcomingNoLongerPendingConstraints
*/
private void visitAdditionalConstraints(Collection<EdgeState> discoveredEdges) {
if (potentiallyActivatedConstraints == null) {
return;
}
for (ModuleIdentifier module : upcomingNoLongerPendingConstraints) {
Collection<DependencyState> dependencyStates = potentiallyActivatedConstraints.get(module);
if (!dependencyStates.isEmpty()) {
for (DependencyState dependencyState : dependencyStates) {
dependencyState = maybeSubstitute(dependencyState, resolveState.getDependencySubstitutionApplicator());
createAndLinkEdgeState(dependencyState, discoveredEdges, previousTraversalExclusions, false);
}
}
}
upcomingNoLongerPendingConstraints = null;
}
/**
* If a component declares that it belongs to a platform, we add an edge to the platform.
*
* @param discoveredEdges the collection of edges for this component
*/
private void visitOwners(Collection<EdgeState> discoveredEdges) {
ImmutableList<? extends VirtualComponentIdentifier> owners = component.getMetadata().getPlatformOwners();
if (!owners.isEmpty()) {
PendingDependenciesVisitor visitor = resolveState.newPendingDependenciesVisitor();
for (VirtualComponentIdentifier owner : owners) {
if (owner instanceof ModuleComponentIdentifier) {
ModuleComponentIdentifier platformId = (ModuleComponentIdentifier) owner;
final ModuleComponentSelector cs = DefaultModuleComponentSelector.newSelector(platformId.getModuleIdentifier(), platformId.getVersion());
// There are 2 possibilities here:
// 1. the "platform" referenced is a real module, in which case we directly add it to the graph
// 2. the "platform" is a virtual, constructed thing, in which case we add virtual edges to the graph
addPlatformEdges(discoveredEdges, platformId, cs);
visitor.markNotPending(platformId.getModuleIdentifier());
}
}
visitor.complete();
}
}
private void addPlatformEdges(Collection<EdgeState> discoveredEdges, ModuleComponentIdentifier platformComponentIdentifier, ModuleComponentSelector platformSelector) {
PotentialEdge potentialEdge = PotentialEdge.of(resolveState, this, platformComponentIdentifier, platformSelector, platformComponentIdentifier);
ComponentResolveMetadata metadata = potentialEdge.metadata;
VirtualPlatformState virtualPlatformState = null;
if (metadata == null || metadata instanceof LenientPlatformResolveMetadata) {
virtualPlatformState = potentialEdge.component.getModule().getPlatformState();
virtualPlatformState.participatingModule(component.getModule());
}
if (metadata == null) {
// the platform doesn't exist, so we're building a lenient one
metadata = new LenientPlatformResolveMetadata(platformComponentIdentifier, potentialEdge.toModuleVersionId, virtualPlatformState, this, resolveState);
potentialEdge.component.setMetadata(metadata);
// And now let's make sure we do not have another version of that virtual platform missing its metadata
potentialEdge.component.getModule().maybeCreateVirtualMetadata(resolveState);
}
if (virtualEdges == null) {
virtualEdges = Lists.newArrayList();
}
EdgeState edge = potentialEdge.edge;
virtualEdges.add(edge);
edge.markUsed();
discoveredEdges.add(edge);
edge.getSelector().use(false);
}
/**
* Execute any dependency substitution rules that apply to this dependency.
*
* This may be better done as a decorator on ConfigurationMetadata.getDependencies()
*/
static DependencyState maybeSubstitute(DependencyState dependencyState, DependencySubstitutionApplicator dependencySubstitutionApplicator) {
DependencySubstitutionApplicator.SubstitutionResult substitutionResult = dependencySubstitutionApplicator.apply(dependencyState.getDependency());
if (substitutionResult.hasFailure()) {
dependencyState.failure = new ModuleVersionResolveException(dependencyState.getRequested(), substitutionResult.getFailure());
return dependencyState;
}
DependencySubstitutionInternal details = substitutionResult.getResult();
if (details != null && details.isUpdated()) {
ArtifactSelectionDetailsInternal artifactSelectionDetails = details.getArtifactSelectionDetails();
if (artifactSelectionDetails.isUpdated()) {
return dependencyState.withTargetAndArtifacts(details.getTarget(), artifactSelectionDetails.getTargetSelectors(), details.getRuleDescriptors());
}
return dependencyState.withTarget(details.getTarget(), details.getRuleDescriptors());
}
return dependencyState;
}
private boolean isExcluded(ExcludeSpec excludeSpec, DependencyState dependencyState) {
DependencyMetadata dependency = dependencyState.getDependency();
if (!resolveState.getEdgeFilter().isSatisfiedBy(dependency)) {
LOGGER.debug("{} is filtered.", dependency);
return true;
}
if (excludeSpec == moduleExclusions.nothing()) {
return false;
}
ModuleIdentifier targetModuleId = dependencyState.getModuleIdentifier();
if (excludeSpec.excludes(targetModuleId)) {
LOGGER.debug("{} is excluded from {} by {}.", targetModuleId, this, excludeSpec);
return true;
}
return false;
}
void addIncomingEdge(EdgeState dependencyEdge) {
if (!incomingEdges.contains(dependencyEdge)) {
incomingEdges.add(dependencyEdge);
incomingHash += dependencyEdge.hashCode();
resolveState.onMoreSelected(this);
if (dependencyEdge.isTransitive()) {
transitiveEdgeCount++;
}
}
}
void removeIncomingEdge(EdgeState dependencyEdge) {
if (incomingEdges.remove(dependencyEdge)) {
incomingHash -= dependencyEdge.hashCode();
if (dependencyEdge.isTransitive()) {
transitiveEdgeCount--;
}
resolveState.onFewerSelected(this);
}
}
@Override
public boolean isSelected() {
return !incomingEdges.isEmpty();
}
public void evict() {
evicted = true;
}
boolean shouldIncludedInGraphResult() {
return isSelected() && !component.getModule().isVirtualPlatform();
}
private ExcludeSpec computeModuleResolutionFilter(List<EdgeState> incomingEdges) {
if (metaData.isExternalVariant()) {
// If the current node represents an external variant, we must not consider its excludes
// because it's some form of "delegation"
return moduleExclusions.excludeAny(
incomingEdges.stream()
.map(EdgeState::getTransitiveExclusions)
.filter(Objects::nonNull)
.collect(Collectors.toSet())
);
}
if (incomingEdges.size() == 1) {
// At the same time if the current node _comes from_ a delegated variant (available-at)
// then we need to take the exclusion filter from the origin node instead
NodeState from = incomingEdges.get(0).getFrom();
if (from.getMetadata().isExternalVariant()) {
return computeModuleResolutionFilter(from.getIncomingEdges());
}
}
ExcludeSpec nodeExclusions = computeNodeExclusions();
if (incomingEdges.isEmpty()) {
return nodeExclusions;
}
return computeExclusionFilter(incomingEdges, nodeExclusions);
}
private ExcludeSpec computeNodeExclusions() {
if (cachedNodeExclusions == null) {
cachedNodeExclusions = moduleExclusions.excludeAny(metaData.getExcludes());
}
return cachedNodeExclusions;
}
private ExcludeSpec computeExclusionFilter(List<EdgeState> incomingEdges, ExcludeSpec nodeExclusions) {
int incomingEdgeCount = incomingEdges.size();
if (sameIncomingEdgesAsPreviousPass(incomingEdgeCount)) {
// if we reach this point it means the node selection was restarted, but
// effectively it has the same incoming edges as before, so we can return
// the result we computed last time
return cachedModuleResolutionFilter;
}
if (incomingEdgeCount == 1) {
return computeExclusionFilterSingleIncomingEdge(incomingEdges.get(0), nodeExclusions);
}
return computeModuleExclusionsManyEdges(incomingEdges, nodeExclusions, incomingEdgeCount);
}
private ExcludeSpec computeModuleExclusionsManyEdges(List<EdgeState> incomingEdges, ExcludeSpec nodeExclusions, int incomingEdgeCount) {
ExcludeSpec nothing = moduleExclusions.nothing();
ExcludeSpec edgeExclusions = null;
Set<ExcludeSpec> excludedByBoth = null;
Set<ExcludeSpec> excludedByEither = null;
for (EdgeState dependencyEdge : incomingEdges) {
if (dependencyEdge.isTransitive()) {
if (edgeExclusions != nothing) {
// Transitive dependency
ExcludeSpec exclusions = dependencyEdge.getExclusions();
if (edgeExclusions == null || exclusions == nothing) {
edgeExclusions = exclusions;
} else if (edgeExclusions != exclusions) {
if (excludedByBoth == null) {
excludedByBoth = Sets.newHashSetWithExpectedSize(incomingEdgeCount);
}
excludedByBoth.add(exclusions);
}
if (edgeExclusions == nothing) {
// if exclusions == nothing, then the intersection will be "nothing"
excludedByBoth = null;
}
}
} else if (isConstraint(dependencyEdge)) {
excludedByEither = collectEdgeConstraint(nodeExclusions, excludedByEither, dependencyEdge, nothing, incomingEdgeCount);
}
}
edgeExclusions = intersectEdgeExclusions(edgeExclusions, excludedByBoth);
nodeExclusions = joinNodeExclusions(nodeExclusions, excludedByEither);
return joinEdgeAndNodeExclusionsThenCacheResult(nodeExclusions, edgeExclusions, incomingEdgeCount);
}
private ExcludeSpec computeExclusionFilterSingleIncomingEdge(EdgeState dependencyEdge, ExcludeSpec nodeExclusions) {
ExcludeSpec exclusions = null;
if (dependencyEdge.isTransitive()) {
exclusions = dependencyEdge.getExclusions();
} else if (isConstraint(dependencyEdge)) {
exclusions = dependencyEdge.getEdgeExclusions();
}
if (exclusions == null) {
exclusions = moduleExclusions.nothing();
}
return joinEdgeAndNodeExclusionsThenCacheResult(nodeExclusions, exclusions, 1);
}
private static boolean isConstraint(EdgeState dependencyEdge) {
return dependencyEdge.getDependencyMetadata().isConstraint();
}
private ExcludeSpec joinEdgeAndNodeExclusionsThenCacheResult(ExcludeSpec nodeExclusions, ExcludeSpec edgeExclusions, int incomingEdgeCount) {
ExcludeSpec result = moduleExclusions.excludeAny(edgeExclusions, nodeExclusions);
// We use a set here because for excludes, order of edges is irrelevant
// so we hit the cache more by using a set
previousIncomingEdgeCount = incomingEdgeCount;
previousIncomingHash = incomingHash;
cachedModuleResolutionFilter = result;
return result;
}
@Nullable
private static Set<ExcludeSpec> collectEdgeConstraint(ExcludeSpec nodeExclusions, @Nullable Set<ExcludeSpec> excludedByEither, EdgeState dependencyEdge, ExcludeSpec nothing, int incomingEdgeCount) {
// Constraint: only consider explicit exclusions declared for this constraint
ExcludeSpec constraintExclusions = dependencyEdge.getEdgeExclusions();
if (constraintExclusions != nothing && constraintExclusions != nodeExclusions) {
if (excludedByEither == null) {
excludedByEither = Sets.newHashSetWithExpectedSize(incomingEdgeCount);
}
excludedByEither.add(constraintExclusions);
}
return excludedByEither;
}
@Nullable
private ExcludeSpec joinNodeExclusions(@Nullable ExcludeSpec nodeExclusions, @Nullable Set<ExcludeSpec> excludedByEither) {
if (excludedByEither != null) {
if (nodeExclusions != null) {
excludedByEither.add(nodeExclusions);
nodeExclusions = moduleExclusions.excludeAny(excludedByEither);
}
}
return nodeExclusions;
}
@Nullable
private ExcludeSpec intersectEdgeExclusions(@Nullable ExcludeSpec edgeExclusions, @Nullable Set<ExcludeSpec> excludedByBoth) {
if (edgeExclusions == moduleExclusions.nothing()) {
return edgeExclusions;
}
if (excludedByBoth != null) {
if (edgeExclusions != null) {
excludedByBoth.add(edgeExclusions);
}
edgeExclusions = moduleExclusions.excludeAll(excludedByBoth);
}
return edgeExclusions;
}
private void collectOwnStrictVersions() {
List<DependencyState> dependencies = dependencies(computeModuleResolutionFilter(incomingEdges));
Set<ModuleIdentifier> constraintsSet = null;
for (DependencyState dependencyState : dependencies) {
constraintsSet = maybeCollectStrictVersions(constraintsSet, dependencyState);
}
storeOwnStrictVersions(constraintsSet);
}
@Nullable
private Set<ModuleIdentifier> maybeCollectStrictVersions(@Nullable Set<ModuleIdentifier> constraintsSet, DependencyState dependencyState) {
if (dependencyState.getDependency().getSelector() instanceof ModuleComponentSelector) {
ModuleComponentSelector selector = (ModuleComponentSelector) dependencyState.getDependency().getSelector();
if (!StringUtils.isEmpty(selector.getVersionConstraint().getStrictVersion())) {
if (constraintsSet == null) {
constraintsSet = Sets.newHashSet();
}
constraintsSet.add(selector.getModuleIdentifier());
}
}
return constraintsSet;
}
private void storeOwnStrictVersions(@Nullable Set<ModuleIdentifier> constraintsSet) {
if (constraintsSet == null) {
ownStrictVersionConstraints = StrictVersionConstraints.EMPTY;
} else {
ownStrictVersionConstraints = StrictVersionConstraints.of(ImmutableSet.copyOf(constraintsSet));
}
}
/**
* This methods computes the intersection of ancestors' strict versions coming in from different edges.
* This is, because only if all paths to this node provides a strict version constraint for a module,
* {@link #versionProvidedByAncestors(DependencyState)} is true for that module.
*
* The result of this method is stored in the 'ancestorsStrictVersionConstraints' field for consumption by downstream nodes.
*
* Since the most common case it that there is only one incoming edge, this case is handled first and, if possible,
* the method returns early.
*/
private void collectAncestorsStrictVersions(List<EdgeState> incomingEdges) {
if (incomingEdges.isEmpty()) {
ancestorsStrictVersionConstraints = StrictVersionConstraints.EMPTY;
return;
}
if (incomingEdges.size() == 1) {
collectAncestorsStrictVersionsSingleEdge(incomingEdges);
return;
}
collectAncestorsStrictVersionsMultiEdges(incomingEdges);
}
private void collectAncestorsStrictVersionsMultiEdges(List<EdgeState> incomingEdges) {
StrictVersionConstraints constraints = null;
for (EdgeState dependencyEdge : incomingEdges) {
StrictVersionConstraints parentStrictVersionConstraints = notNull(dependencyEdge.getFrom().ownStrictVersionConstraints);
StrictVersionConstraints parentAncestorsStrictVersionConstraints = notNull(dependencyEdge.getFrom().ancestorsStrictVersionConstraints);
StrictVersionConstraints parentEndorsedStrictVersionConstraints = getEndorsedStrictVersions(dependencyEdge);
if (constraints == null) {
constraints = parentStrictVersionConstraints
.union(parentAncestorsStrictVersionConstraints)
.union(parentEndorsedStrictVersionConstraints);
} else {
constraints = constraints.intersect(
parentStrictVersionConstraints
.union(parentAncestorsStrictVersionConstraints)
.union(parentEndorsedStrictVersionConstraints)
);
}
if (constraints == StrictVersionConstraints.EMPTY) {
ancestorsStrictVersionConstraints = constraints;
return;
}
}
ancestorsStrictVersionConstraints = constraints;
}
private void collectAncestorsStrictVersionsSingleEdge(List<EdgeState> incomingEdges) {
EdgeState dependencyEdge = incomingEdges.get(0);
StrictVersionConstraints parentStrictVersionConstraints = notNull(dependencyEdge.getFrom().ownStrictVersionConstraints);
StrictVersionConstraints parentAncestorsStrictVersionConstraints = notNull(dependencyEdge.getFrom().ancestorsStrictVersionConstraints);
StrictVersionConstraints parentEndorsedStrictVersionConstraints = getEndorsedStrictVersions(dependencyEdge);
ancestorsStrictVersionConstraints = parentStrictVersionConstraints
.union(parentAncestorsStrictVersionConstraints)
.union(parentEndorsedStrictVersionConstraints);
}
private static StrictVersionConstraints notNull(@Nullable StrictVersionConstraints strictVersionConstraints) {
return strictVersionConstraints == null ? StrictVersionConstraints.EMPTY : strictVersionConstraints;
}
private StrictVersionConstraints getEndorsedStrictVersions(EdgeState incomingEdge) {
if (incomingEdge.getFrom().endorsesStrictVersionsFrom == null) {
return StrictVersionConstraints.EMPTY;
}
boolean filterOwn = false;
StrictVersionConstraints singleStrictVersionConstraints = StrictVersionConstraints.EMPTY;
Set<ModuleIdentifier> collectedConstraints = null;
for (EdgeState edgeState : incomingEdge.getFrom().endorsesStrictVersionsFrom) {
if (edgeState == incomingEdge) {
// These are my own constraints. I can not treat them as inherited,
// because that assumes that they are defined in another node as well and might be ignored.
filterOwn = true;
continue;
}
ComponentState targetComponent = edgeState.getTargetComponent();
if (targetComponent != null) { // may be null if the build is about to fail
for (NodeState sourceNode : targetComponent.getNodes()) {
if (sourceNode.ownStrictVersionConstraints == null) {
// node's dependencies were not yet visited
sourceNode.collectOwnStrictVersions();
}
if (singleStrictVersionConstraints.isEmpty()) {
singleStrictVersionConstraints = sourceNode.ownStrictVersionConstraints;
} else {
if (collectedConstraints == null) {
collectedConstraints = Sets.newHashSet();
collectedConstraints.addAll(singleStrictVersionConstraints.getModules());
}
collectedConstraints.addAll(sourceNode.ownStrictVersionConstraints.getModules());
}
}
}
}
if (filterOwn) {
Set<ModuleIdentifier> resultSet;
if (collectedConstraints != null) {
resultSet = collectedConstraints;
} else {
resultSet = singleStrictVersionConstraints.getModules();
}
if (ownStrictVersionConstraints == null) {
collectOwnStrictVersions();
}
for (ModuleIdentifier ownConstraint : ownStrictVersionConstraints.getModules()) {
if (resultSet.contains(ownConstraint)) {
if (collectedConstraints == null) {
collectedConstraints = Sets.newHashSet();
collectedConstraints.addAll(singleStrictVersionConstraints.getModules());
}
collectedConstraints.remove(ownConstraint);
}
}
}
if (collectedConstraints != null) {
return StrictVersionConstraints.of(collectedConstraints);
} else {
return singleStrictVersionConstraints;
}
}
void collectEndorsedStrictVersions(List<EdgeState> dependencies) {
if (endorsesStrictVersionsFrom != null) {
// we are revisiting this node
endorsesStrictVersionsFrom.clear();
}
for (EdgeState edgeState : dependencies) {
if (!DependencyGraphBuilder.ENDORSE_STRICT_VERSIONS_DEPENDENCY_SPEC.isSatisfiedBy(edgeState)) {
continue;
}
if (endorsesStrictVersionsFrom == null) {