1   /*
2    * Copyright 2018 LINE Corporation
3    *
4    * LINE Corporation licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package com.linecorp.centraldogma.client.armeria;
17  
18  import static java.util.Objects.requireNonNull;
19  
20  import java.util.List;
21  import java.util.Set;
22  import java.util.concurrent.CompletableFuture;
23  
24  import com.google.common.annotations.VisibleForTesting;
25  import com.google.common.collect.ImmutableList;
26  import com.google.common.collect.ImmutableSortedSet;
27  
28  import com.linecorp.armeria.client.Endpoint;
29  import com.linecorp.armeria.client.endpoint.DynamicEndpointGroup;
30  import com.linecorp.armeria.client.endpoint.EndpointGroup;
31  import com.linecorp.armeria.client.endpoint.EndpointSelectionStrategy;
32  
33  final class CompositeEndpointGroup extends DynamicEndpointGroup {
34  
35      private final List<EndpointGroup> groups;
36  
37      CompositeEndpointGroup(Iterable<EndpointGroup> groups, EndpointSelectionStrategy selectionStrategy) {
38          super(requireNonNull(selectionStrategy, "selectionStrategy"));
39          this.groups = ImmutableList.copyOf(requireNonNull(groups, "groups"));
40  
41          // Add the listener for all groups.
42          this.groups.forEach(g -> g.addListener(this::onEndpointUpdate));
43  
44          // Set the initial list of Endpoints if possible.
45          final Set<Endpoint> initialEndpoints = collectEndpoints();
46          if (!initialEndpoints.isEmpty()) {
47              setEndpoints(initialEndpoints);
48          }
49      }
50  
51      @VisibleForTesting
52      List<EndpointGroup> groups() {
53          return groups;
54      }
55  
56      private void onEndpointUpdate(@SuppressWarnings("unused") List<Endpoint> unused) {
57          setEndpoints(collectEndpoints());
58      }
59  
60      private Set<Endpoint> collectEndpoints() {
61          final ImmutableSortedSet.Builder<Endpoint> initialEndpointsBuilder = ImmutableSortedSet.naturalOrder();
62          groups.forEach(g -> initialEndpointsBuilder.addAll(g.endpoints()));
63          return initialEndpointsBuilder.build();
64      }
65  
66      @Override
67      protected void doCloseAsync(CompletableFuture<?> future) {
68          try {
69              groups.forEach(EndpointGroup::close);
70          } finally {
71              future.complete(null);
72          }
73      }
74  }