// Copyright 2017 The Bazel Authors. All rights reserved.
//
// 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 build.buildfarm.server;

import build.buildfarm.common.DigestUtil;
import build.buildfarm.instance.Instance;
import build.bazel.remote.execution.v2.ActionCacheGrpc;
import build.bazel.remote.execution.v2.ActionResult;
import build.bazel.remote.execution.v2.GetActionResultRequest;
import build.bazel.remote.execution.v2.UpdateActionResultRequest;
import io.grpc.Status;
import io.grpc.StatusException;
import io.grpc.stub.StreamObserver;
import java.util.logging.Logger;

public class ActionCacheService extends ActionCacheGrpc.ActionCacheImplBase {
  private static final Logger logger = Logger.getLogger(ActionCacheService.class.getName());

  private final Instances instances;

  public ActionCacheService(Instances instances) {
    this.instances = instances;
  }

  @Override
  public void getActionResult(
      GetActionResultRequest request,
      StreamObserver<ActionResult> responseObserver) {
    Instance instance;
    try {
      instance = instances.get(request.getInstanceName());
    } catch (InstanceNotFoundException e) {
      responseObserver.onError(BuildFarmInstances.toStatusException(e));
      return;
    }

    ActionResult actionResult = instance.getActionResult(
        DigestUtil.asActionKey(request.getActionDigest()));
    if (actionResult == null) {
      responseObserver.onError(Status.NOT_FOUND.asException());
      return;
    }

    logger.info("GetActionResult for ActionKey " + DigestUtil.toString(request.getActionDigest()));
    responseObserver.onNext(actionResult);
    responseObserver.onCompleted();
  }

  @Override
  public void updateActionResult(
      UpdateActionResultRequest request,
      StreamObserver<ActionResult> responseObserver) {
    Instance instance;
    try {
      instance = instances.get(request.getInstanceName());
    } catch (InstanceNotFoundException e) {
      responseObserver.onError(BuildFarmInstances.toStatusException(e));
      return;
    }

    ActionResult actionResult = request.getActionResult();
    try {
      instance.putActionResult(
          DigestUtil.asActionKey(request.getActionDigest()),
          actionResult);

      responseObserver.onNext(actionResult);
      responseObserver.onCompleted();
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }
  }
}

@@ -642,16 +642,56 @@
 erver;%0A%0A
+import static java.lang.String.format;%0A%0A
 import b
@@ -724,16 +724,16 @@
 stUtil;%0A
-
 import b
@@ -1044,24 +1044,59 @@
 .grpc.Status
+.Code;%0Aimport io.grpc.StatusRuntime
 Exception;%0Ai
@@ -1820,32 +1820,44 @@
  return;%0A    %7D%0A%0A
+    try %7B%0A  
     ActionResult
@@ -1898,32 +1898,34 @@
 Result(%0A        
+ 
+ 
 DigestUtil.asAct
@@ -1964,16 +1964,18 @@
 ));%0A    
+  
 if (acti
@@ -1992,32 +1992,34 @@
 = null) %7B%0A      
+ 
+ 
 responseObserver
@@ -2062,39 +2062,37 @@
 n());%0A      
-return;
+%7D else %7B
 %0A    
-%7D%0A%0A
     logger.i
@@ -2094,12 +2094,20 @@
 ger.
+f
 in
-fo
+er(format
 (%22Ge
@@ -2138,11 +2138,12 @@
 Key 
-%22 +
+%25s%22,
  Dig
@@ -2186,22 +2186,27 @@
 gest()))
+)
 ;%0A    
+   
+ 
 response
@@ -2232,24 +2232,28 @@
 ionResult);%0A
+    
     response
@@ -2276,16 +2276,230 @@
 eted();%0A
+      %7D%0A    %7D catch (StatusRuntimeException e) %7B%0A      Status status = Status.fromThrowable(e);%0A      if (status.getCode() != Code.CANCELLED) %7B%0A        responseObserver.onError(status.asException());%0A      %7D%0A    %7D%0A
   %7D%0A%0A  @

Handle Status exceptions in getActionResult