1   /*
2    * Copyright 2017 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  
17  package com.linecorp.centraldogma.client.armeria.legacy;
18  
19  import java.util.List;
20  
21  import com.linecorp.armeria.client.Client;
22  import com.linecorp.armeria.client.ClientRequestContext;
23  import com.linecorp.armeria.client.RpcClient;
24  import com.linecorp.armeria.client.SimpleDecoratingRpcClient;
25  import com.linecorp.armeria.common.RpcRequest;
26  import com.linecorp.armeria.common.RpcResponse;
27  import com.linecorp.armeria.common.util.TimeoutMode;
28  import com.linecorp.centraldogma.internal.api.v1.WatchTimeout;
29  
30  /**
31   * Decorates a {@link Client} to enlarge responseTimeout when requesting watchFile or watchRepository.
32   */
33  class LegacyCentralDogmaTimeoutScheduler extends SimpleDecoratingRpcClient {
34  
35      /**
36       * Creates a new instance that decorates the specified {@link Client}.
37       */
38      LegacyCentralDogmaTimeoutScheduler(RpcClient delegate) {
39          super(delegate);
40      }
41  
42      @Override
43      public RpcResponse execute(ClientRequestContext ctx, RpcRequest req) throws Exception {
44          final long responseTimeoutMillis = ctx.responseTimeoutMillis();
45          if (responseTimeoutMillis > 0) {
46              final String method = req.method();
47              if ("watchFile".equals(method) || "watchRepository".equals(method)) {
48                  final List<Object> params = req.params();
49                  final long timeout = (Long) params.get(params.size() - 1);
50                  if (timeout > 0) {
51                      ctx.setResponseTimeoutMillis(TimeoutMode.EXTEND,
52                                                   WatchTimeout.availableTimeout(timeout, responseTimeoutMillis));
53                  }
54              }
55          }
56          return unwrap().execute(ctx, req);
57      }
58  }