| 28 | import javax.annotation.Nullable; |
| 29 | |
| 30 | final class AddressFilter { |
| 31 | @ResolutionResultAttr |
| 32 | static final Attributes.Key<PathChain> PATH_CHAIN_KEY = |
| 33 | Attributes.Key.create("io.grpc.xds.AddressFilter.PATH_CHAIN_KEY"); |
| 34 | |
| 35 | // Prevent instantiation. |
| 36 | private AddressFilter() {} |
| 37 | |
| 38 | /** |
| 39 | * Returns a new EquivalentAddressGroup by setting a path filter to the given |
| 40 | * EquivalentAddressGroup. This method does not modify the input address. |
| 41 | */ |
| 42 | static EquivalentAddressGroup setPathFilter(EquivalentAddressGroup address, List<String> names) { |
| 43 | checkNotNull(address, "address"); |
| 44 | checkNotNull(names, "names"); |
| 45 | Attributes.Builder attrBuilder = address.getAttributes().toBuilder() |
| 46 | .set(PATH_CHAIN_KEY, createPathChain(names)); |
| 47 | return new EquivalentAddressGroup(address.getAddresses(), attrBuilder.build()); |
| 48 | } |
| 49 | |
| 50 | /** |
| 51 | * Creates a PathChain that can be set in an EquivalentAddressGroup's Attributes as a value of |
| 52 | * PATH_CHAIN_KEY. |
| 53 | */ |
| 54 | @Nullable static PathChain createPathChain(List<String> names) { |
| 55 | checkNotNull(names, "names"); |
| 56 | PathChain current = null; |
| 57 | ListIterator<String> iter = names.listIterator(names.size()); |
| 58 | while (iter.hasPrevious()) { |
| 59 | current = new PathChain(iter.previous(), current); |
| 60 | } |
| 61 | return current; |
| 62 | } |
| 63 | |
| 64 | /** |
| 65 | * Returns the next level hierarchical addresses derived from the given hierarchical addresses |
| 66 | * with the given filter name (any non-hierarchical addresses in the input will be ignored). |
| 67 | * This method does not modify the input addresses. |
| 68 | */ |
| 69 | static List<EquivalentAddressGroup> filter(List<EquivalentAddressGroup> addresses, String name) { |
| 70 | checkNotNull(addresses, "addresses"); |
| 71 | checkNotNull(name, "name"); |
| 72 | List<EquivalentAddressGroup> filteredAddresses = new ArrayList<>(); |
| 73 | for (EquivalentAddressGroup address : addresses) { |
| 74 | PathChain pathChain = address.getAttributes().get(PATH_CHAIN_KEY); |
| 75 | if (pathChain != null && pathChain.name.equals(name)) { |
| 76 | Attributes filteredAddressAttrs = |
| 77 | address.getAttributes().toBuilder().set(PATH_CHAIN_KEY, pathChain.next).build(); |
| 78 | filteredAddresses.add( |
| 79 | new EquivalentAddressGroup(address.getAddresses(), filteredAddressAttrs)); |
| 80 | } |
| 81 | } |
| 82 | return Collections.unmodifiableList(filteredAddresses); |
| 83 | } |
| 84 | |
| 85 | static final class PathChain { |
| 86 | final String name; |
| 87 | @Nullable final PathChain next; |