diff --git a/src/main/java/ai/chalk/client/AggregateBackfills.java b/src/main/java/ai/chalk/client/AggregateBackfills.java index bfddd34..def542d 100644 --- a/src/main/java/ai/chalk/client/AggregateBackfills.java +++ b/src/main/java/ai/chalk/client/AggregateBackfills.java @@ -6,6 +6,7 @@ import ai.chalk.exceptions.ServerError; import ai.chalk.models.AggregateBackfillParams; import ai.chalk.models.AggregateBackfillResponse; +import ai.chalk.models.GetAggregateBackfillJobParams; import ai.chalk.protos.chalk.aggregate.v1.AggregateBackfill; import ai.chalk.protos.chalk.aggregate.v1.AggregateBackfillJob; import ai.chalk.protos.chalk.aggregate.v1.AggregateBackfillMode; @@ -29,7 +30,8 @@ import java.util.List; /** - * Triggers aggregate backfills against the API server's AggregateService. Mirrors + * Triggers and looks up aggregate backfills against the API server's AggregateService, + * over either client's {@link AggregateRpc}. Mirrors * {@code ChalkGRPCClient.trigger_aggregate_backfill} in the Python client. * *

A single CreateAggregateBackfillV2 call plans and creates every job server-side. @@ -43,13 +45,13 @@ final class AggregateBackfills { private AggregateBackfills() {} static AggregateBackfillResponse trigger( - AggregateServiceGrpc.AggregateServiceBlockingStub stub, + AggregateRpc rpc, AggregateBackfillParams params ) throws ChalkException { validate(params); CreateAggregateBackfillV2Request request = buildV2Request(params); - CreateAggregateBackfillV2Response response = createV2(stub, request); + CreateAggregateBackfillV2Response response = createV2(rpc, request); if (response != null) { return AggregateBackfillConverter.responseDecode(response); } @@ -75,7 +77,25 @@ static AggregateBackfillResponse trigger( "This Chalk server does not support server-side aggregate backfill planning. " + "Falling back to client-side planning." ); - return triggerLegacy(stub, params, request.getAllowEmptyTiles()); + return triggerLegacy(rpc, params, request.getAllowEmptyTiles()); + } + + static @Nullable ai.chalk.models.AggregateBackfillJob get( + AggregateRpc rpc, + GetAggregateBackfillJobParams params + ) throws ChalkException { + if (params.getAggregateBackfillId() == null || params.getAggregateBackfillId().isEmpty()) { + throw new ClientException("aggregateBackfillId is required to get an aggregate backfill job."); + } + GetAggregateBackfillJobResponse response = rpc.call( + AggregateServiceGrpc.getGetAggregateBackfillJobMethod(), + GetAggregateBackfillJobRequest.newBuilder() + .setAggregateBackfillId(params.getAggregateBackfillId()) + .build() + ); + // An unset `job` reads back as an empty message, which would otherwise be returned + // as a job with no id. + return response.hasJob() ? AggregateBackfillConverter.jobDecode(response.getJob()) : null; } static void validate(AggregateBackfillParams params) throws ClientException { @@ -145,11 +165,11 @@ static CreateAggregateBackfillV2Request buildV2Request(AggregateBackfillParams p * mistaken for version skew. */ private static @Nullable CreateAggregateBackfillV2Response createV2( - AggregateServiceGrpc.AggregateServiceBlockingStub stub, + AggregateRpc rpc, CreateAggregateBackfillV2Request request - ) throws AggregateBackfillException { + ) throws ChalkException { try { - return stub.createAggregateBackfillV2(request); + return rpc.call(AggregateServiceGrpc.getCreateAggregateBackfillV2Method(), request); } catch (StatusRuntimeException e) { Status.Code code = e.getStatus().getCode(); if (code == Status.Code.UNIMPLEMENTED) { @@ -189,10 +209,10 @@ static CreateAggregateBackfillV2Request buildV2Request(AggregateBackfillParams p * cannot be read back. */ private static AggregateBackfillResponse triggerLegacy( - AggregateServiceGrpc.AggregateServiceBlockingStub stub, + AggregateRpc rpc, AggregateBackfillParams params, boolean allowEmptyTiles - ) throws AggregateBackfillException { + ) throws ChalkException { List queryTags = params.getQueryTags() == null ? List.of() : params.getQueryTags(); var userParams = AggregateBackfillUserParams.newBuilder() @@ -212,7 +232,8 @@ private static AggregateBackfillResponse triggerLegacy( userParams.setInputSql(params.getInputSql()); } - PlanAggregateBackfillResponse planResponse = stub.planAggregateBackfill( + PlanAggregateBackfillResponse planResponse = rpc.call( + AggregateServiceGrpc.getPlanAggregateBackfillMethod(), PlanAggregateBackfillRequest.newBuilder().setParams(userParams).build() ); if (planResponse.getErrorsCount() > 0) { @@ -252,7 +273,10 @@ private static AggregateBackfillResponse triggerLegacy( createRequest.setResourceGroup(params.getResourceGroup()); } - CreateAggregateBackfillJobResponse createResponse = stub.createAggregateBackfillJob(createRequest.build()); + CreateAggregateBackfillJobResponse createResponse = rpc.call( + AggregateServiceGrpc.getCreateAggregateBackfillJobMethod(), + createRequest.build() + ); if (createResponse.getErrorsCount() > 0) { List errors = new ArrayList<>(); for (var error : createResponse.getErrorsList()) { @@ -265,7 +289,8 @@ private static AggregateBackfillResponse triggerLegacy( AggregateBackfillJob job = null; try { - GetAggregateBackfillJobResponse getResponse = stub.getAggregateBackfillJob( + GetAggregateBackfillJobResponse getResponse = rpc.call( + AggregateServiceGrpc.getGetAggregateBackfillJobMethod(), GetAggregateBackfillJobRequest.newBuilder().setAggregateBackfillId(aggregateBackfillId).build() ); // An unset `job` reads back as an empty message, which would otherwise be diff --git a/src/main/java/ai/chalk/client/AggregateRpc.java b/src/main/java/ai/chalk/client/AggregateRpc.java new file mode 100644 index 0000000..6ac02ec --- /dev/null +++ b/src/main/java/ai/chalk/client/AggregateRpc.java @@ -0,0 +1,24 @@ +package ai.chalk.client; + +import ai.chalk.exceptions.ChalkException; +import io.grpc.MethodDescriptor; +import io.grpc.stub.AbstractStub; +import io.grpc.stub.ClientCalls; + +/** + * Sends one unary call to the API server's AggregateService, so {@link AggregateBackfills} + * runs the same logic over gRPC and over HTTP. Either way, an RPC error is thrown as an + * {@link io.grpc.StatusRuntimeException} carrying the server's status code. + */ +interface AggregateRpc { + RespT call(MethodDescriptor method, ReqT request) throws ChalkException; + + static AggregateRpc grpc(AbstractStub stub) { + return new AggregateRpc() { + @Override + public RespT call(MethodDescriptor method, ReqT request) { + return ClientCalls.blockingUnaryCall(stub.getChannel(), method, stub.getCallOptions(), request); + } + }; + } +} diff --git a/src/main/java/ai/chalk/client/ChalkClient.java b/src/main/java/ai/chalk/client/ChalkClient.java index 89ba4df..0f31849 100644 --- a/src/main/java/ai/chalk/client/ChalkClient.java +++ b/src/main/java/ai/chalk/client/ChalkClient.java @@ -296,8 +296,6 @@ default DeleteFeaturesResult deleteFeatures(DeleteFeaturesParams params) throws * operation as the {@code chalk aggregate backfill} CLI command. *

See {@link AggregateBackfillParams} for more details on the parameters. * - *

This is supported only by the gRPC client; see {@link ChalkClient#createGrpc()}. - * *

* Example usage: *

@@ -329,13 +327,31 @@ default DeleteFeaturesResult deleteFeatures(DeleteFeaturesParams params) throws
      * @throws ChalkException if the parameters are invalid, or the server does not support a
      *         requested option
      */
-    default AggregateBackfillResponse triggerAggregateBackfill(AggregateBackfillParams params)
-            throws ChalkException {
-        throw new ClientException(
-                "triggerAggregateBackfill is only supported by the gRPC client. Build one with "
-                        + "ChalkClient.builder().withGrpc().build() or ChalkClient.createGrpc()."
-        );
-    }
+    AggregateBackfillResponse triggerAggregateBackfill(AggregateBackfillParams params)
+            throws ChalkException;
+
+    /**
+     * GetAggregateBackfillJob looks up an aggregate backfill by id, e.g. to poll the status
+     * of a backfill started with {@link #triggerAggregateBackfill}.
+     *
+     * 

+ * Example usage: + *

+     *         {@code
+     *         AggregateBackfillJob job = client.getAggregateBackfillJob(
+     *             GetAggregateBackfillJobParams.builder()
+     *                 .withAggregateBackfillId(backfillId)
+     *                 .build()
+     *         );
+     *         AggregateBackfillStatus status = job.getStatus();
+     *         }
+     *     
+ *

+ * + * @return {@link AggregateBackfillJob}, or null if the server returns no job + */ + AggregateBackfillJob getAggregateBackfillJob(GetAggregateBackfillJobParams params) + throws ChalkException; diff --git a/src/main/java/ai/chalk/client/ChalkClientImpl.java b/src/main/java/ai/chalk/client/ChalkClientImpl.java index 5a977e3..d57b715 100644 --- a/src/main/java/ai/chalk/client/ChalkClientImpl.java +++ b/src/main/java/ai/chalk/client/ChalkClientImpl.java @@ -15,24 +15,37 @@ import ai.chalk.internal.request.models.PingRequest; import ai.chalk.internal.request.models.PingResponse; import ai.chalk.internal.request.models.SendRequestParams; +import ai.chalk.models.AggregateBackfillJob; +import ai.chalk.models.AggregateBackfillParams; +import ai.chalk.models.AggregateBackfillResponse; import ai.chalk.models.DeleteFeaturesParams; import ai.chalk.models.DeleteFeaturesResult; +import ai.chalk.models.GetAggregateBackfillJobParams; import ai.chalk.models.OnlineQueryParamsComplete; import ai.chalk.models.OnlineQueryResult; import ai.chalk.models.QueryMeta; import ai.chalk.models.UploadFeaturesParams; import ai.chalk.models.UploadFeaturesResult; import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategies; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import io.grpc.MethodDescriptor; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.memory.RootAllocator; import org.apache.arrow.vector.*; import org.apache.arrow.vector.table.Table; +import javax.annotation.Nullable; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; +import java.time.Duration; import java.util.*; public class ChalkClientImpl implements ChalkClient { @@ -46,6 +59,19 @@ public class ChalkClientImpl implements ChalkClient { private static final System.Logger logger = System.getLogger(ChalkClientImpl.class.getName()); private final RootAllocator allocator = new RootAllocator(FeatherProcessor.ALLOCATOR_SIZE_ROOT); + // Connect protocol headers for AggregateService calls. The rest mirror the gRPC client's + // AggregateService calls, which carry no deployment-routing headers. + private static final Map CONNECT_HEADERS = new HashMap<>(); + static { + CONNECT_HEADERS.put("Content-Type", "application/proto"); + CONNECT_HEADERS.put("Accept", "application/proto"); + CONNECT_HEADERS.put("Connect-Protocol-Version", "1"); + CONNECT_HEADERS.put("x-chalk-server", ServerType.SERVER.headerName()); + CONNECT_HEADERS.put("X-Chalk-Deployment-Type", null); + CONNECT_HEADERS.put("X-Chalk-Branch-Id", null); + CONNECT_HEADERS.put("X-Chalk-Deployment-Tag", null); + } + public ChalkClientImpl(BuilderImpl config) throws ChalkException { ResolvedConfig resolvedConfig = this.resolveConfig(config); this.apiServer = resolvedConfig.apiServer(); @@ -366,4 +392,68 @@ public void printConfig() { public void close() { this.allocator.close(); } + + @Override + public AggregateBackfillResponse triggerAggregateBackfill(AggregateBackfillParams params) + throws ChalkException { + return AggregateBackfills.trigger(aggregateRpc(params.getTimeout(), params.getEnvironmentId()), params); + } + + @Override + public AggregateBackfillJob getAggregateBackfillJob(GetAggregateBackfillJobParams params) + throws ChalkException { + return AggregateBackfills.get(aggregateRpc(params.getTimeout(), params.getEnvironmentId()), params); + } + + /* + * Calls the API server's AggregateService over plain HTTP with the Connect protocol, which + * the server accepts alongside gRPC (the chalk CLI calls it this way). + */ + private AggregateRpc aggregateRpc(@Nullable Duration timeout, @Nullable String environmentId) { + return new AggregateRpc() { + @Override + public RespT call(MethodDescriptor method, ReqT request) + throws ChalkException { + byte[] body; + try (InputStream stream = method.streamRequest(request)) { + body = stream.readAllBytes(); + } catch (IOException e) { + throw new ClientException("Failed to serialize " + method.getFullMethodName(), e); + } + HttpResponse response = handler.sendRequest( + new SendRequestParams.Builder(timeout) + .path("/" + method.getFullMethodName()) + .body(body) + .method("POST") + .isEngineRequest(false) + .environmentOverride(environmentId) + .headers(CONNECT_HEADERS) + .returnErrorResponses(true) + .build() + ); + if (response.statusCode() != 200) { + throw connectError(response); + } + return method.parseResponse(new ByteArrayInputStream(response.body())); + } + }; + } + + /* + * Decodes a Connect error body ({"code": "invalid_argument", "message": "..."}) into the + * StatusRuntimeException the gRPC client would throw, so AggregateBackfills handles both alike. + */ + private static StatusRuntimeException connectError(HttpResponse response) { + Status status = Status.UNKNOWN.withDescription("HTTP " + response.statusCode()); + try { + JsonNode error = new ObjectMapper().readTree(response.body()); + // Connect codes are gRPC's in snake_case, except "canceled". + String code = error.path("code").asText().toUpperCase(Locale.ROOT).replace("CANCELED", "CANCELLED"); + status = Status.fromCode(Status.Code.valueOf(code)) + .withDescription(error.path("message").asText(null)); + } catch (IOException | IllegalArgumentException ignored) { + // Not a Connect error body (e.g. from a proxy), so keep the HTTP status. + } + return status.asRuntimeException(); + } } diff --git a/src/main/java/ai/chalk/client/GRPCClient.java b/src/main/java/ai/chalk/client/GRPCClient.java index ddffbb6..418f1e3 100644 --- a/src/main/java/ai/chalk/client/GRPCClient.java +++ b/src/main/java/ai/chalk/client/GRPCClient.java @@ -7,8 +7,10 @@ import ai.chalk.internal.arrow.FeatherProcessor; import ai.chalk.internal.config.Loader; import ai.chalk.internal.config.models.ProjectToken; +import ai.chalk.models.AggregateBackfillJob; import ai.chalk.models.AggregateBackfillParams; import ai.chalk.models.AggregateBackfillResponse; +import ai.chalk.models.GetAggregateBackfillJobParams; import ai.chalk.models.OnlineQueryMultiResult; import ai.chalk.models.OnlineQueryParamsComplete; import ai.chalk.models.OnlineQueryResult; @@ -795,10 +797,20 @@ public UploadFeaturesResult uploadFeatures(UploadFeaturesParams params) throws C @Override public AggregateBackfillResponse triggerAggregateBackfill(AggregateBackfillParams params) throws ChalkException { - return AggregateBackfills.trigger( - this.stubsProvider.getAggregateStub(Optional.ofNullable(params.getTimeout())) - .withInterceptors(this.getRequestHeaderInterceptor(params.getEnvironmentId(), null)), - params + return AggregateBackfills.trigger(aggregateRpc(params.getTimeout(), params.getEnvironmentId()), params); + } + + @Override + public AggregateBackfillJob getAggregateBackfillJob(GetAggregateBackfillJobParams params) + throws ChalkException { + return AggregateBackfills.get(aggregateRpc(params.getTimeout(), params.getEnvironmentId()), params); + } + + private AggregateRpc aggregateRpc(@Nullable Duration timeout, @Nullable String environmentId) + throws ClientException { + return AggregateRpc.grpc( + this.stubsProvider.getAggregateStub(Optional.ofNullable(timeout)) + .withInterceptors(this.getRequestHeaderInterceptor(environmentId, null)) ); } diff --git a/src/main/java/ai/chalk/internal/request/RequestHandler.java b/src/main/java/ai/chalk/internal/request/RequestHandler.java index f160c36..c29ed76 100644 --- a/src/main/java/ai/chalk/internal/request/RequestHandler.java +++ b/src/main/java/ai/chalk/internal/request/RequestHandler.java @@ -22,6 +22,7 @@ import java.time.ZoneOffset; import java.util.HashMap; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.stream.Stream; @@ -166,6 +167,10 @@ public HttpResponse sendRequest(SendRequestParams args) throws ChalkExce args.getBranch(), args.getQueryName() ); + if (args.getHeaders() != null) { + headers.putAll(args.getHeaders()); + headers.values().removeIf(Objects::isNull); + } HttpRequest.Builder builder = HttpRequest.newBuilder(); if (args.getRequestLevelTimeout() != null) { @@ -223,7 +228,7 @@ public HttpResponse sendRequest(SendRequestParams args) throws ChalkExce } } - if (response.statusCode() != 200) { + if (response.statusCode() != 200 && !args.isReturnErrorResponses()) { throw getHttpException(response, request.uri().toString()); } diff --git a/src/main/java/ai/chalk/internal/request/models/SendRequestParams.java b/src/main/java/ai/chalk/internal/request/models/SendRequestParams.java index 531b991..ea4a1ac 100644 --- a/src/main/java/ai/chalk/internal/request/models/SendRequestParams.java +++ b/src/main/java/ai/chalk/internal/request/models/SendRequestParams.java @@ -5,6 +5,7 @@ import javax.annotation.Nullable; import java.time.Duration; +import java.util.Map; import java.util.Optional; @@ -23,6 +24,10 @@ public class SendRequestParams { private String queryName; private Boolean isEngineRequest; private Duration requestLevelTimeout; + /** Overrides the default headers. A null value removes that header. */ + private Map headers; + /** If true, non-200 responses are returned rather than thrown. */ + private boolean returnErrorResponses; public static class Builder { private Object body; @@ -35,6 +40,8 @@ public static class Builder { private String queryName; private Boolean isEngineRequest; private @Nullable Duration requestLevelTimeout; + private @Nullable Map headers; + private boolean returnErrorResponses; public Builder(Duration requestLevelTimeout) { this.requestLevelTimeout = requestLevelTimeout; @@ -86,11 +93,21 @@ public Builder isEngineRequest(Boolean isEngineRequest) { return this; } + public Builder headers(Map headers) { + this.headers = headers; + return this; + } + + public Builder returnErrorResponses(boolean returnErrorResponses) { + this.returnErrorResponses = returnErrorResponses; + return this; + } + public SendRequestParams build() { return new SendRequestParams( body, method, path, dontRefresh, environmentOverride, previewDeploymentId, branch, queryName, - isEngineRequest, requestLevelTimeout + isEngineRequest, requestLevelTimeout, headers, returnErrorResponses ); } } diff --git a/src/main/java/ai/chalk/models/GetAggregateBackfillJobParams.java b/src/main/java/ai/chalk/models/GetAggregateBackfillJobParams.java new file mode 100644 index 0000000..dde2433 --- /dev/null +++ b/src/main/java/ai/chalk/models/GetAggregateBackfillJobParams.java @@ -0,0 +1,58 @@ +package ai.chalk.models; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import javax.annotation.Nullable; +import java.time.Duration; + + +/** + * Parameters for looking up an aggregate backfill, e.g. to poll its status. + */ +@AllArgsConstructor @Getter +public class GetAggregateBackfillJobParams { + /** + * The aggregate backfill id, as returned by {@code AggregateBackfillResponse.getJob().getId()}. + */ + private final String aggregateBackfillId; + @Nullable + private final String environmentId; + @Nullable + private final Duration timeout; + + @AllArgsConstructor + @NoArgsConstructor + public static class Builder { + protected String aggregateBackfillId; + protected String environmentId; + protected Duration timeout; + + public GetAggregateBackfillJobParams build() { + return new GetAggregateBackfillJobParams( + this.aggregateBackfillId, + this.environmentId, + this.timeout); + } + + public Builder withAggregateBackfillId(String aggregateBackfillId) { + this.aggregateBackfillId = aggregateBackfillId; + return this; + } + + public Builder withEnvironmentId(String environmentId) { + this.environmentId = environmentId; + return this; + } + + public Builder withTimeout(Duration timeout) { + this.timeout = timeout; + return this; + } + } + + public static Builder builder() { + return new Builder(); + } +} diff --git a/src/test/java/ai/chalk/client/TestAggregateBackfill.java b/src/test/java/ai/chalk/client/TestAggregateBackfill.java index c274141..9ace55e 100644 --- a/src/test/java/ai/chalk/client/TestAggregateBackfill.java +++ b/src/test/java/ai/chalk/client/TestAggregateBackfill.java @@ -206,7 +206,7 @@ private static AggregateBackfillParams.Builder params() { } private AggregateBackfillResponse trigger(AggregateBackfillParams.Builder params) throws Exception { - return AggregateBackfills.trigger(stub, params.build()); + return AggregateBackfills.trigger(AggregateRpc.grpc(stub), params.build()); } private static long seconds(ZonedDateTime value) { diff --git a/src/test/java/ai/chalk/client/TestAggregateBackfillClient.java b/src/test/java/ai/chalk/client/TestAggregateBackfillClient.java index ff84cd7..2a8b5b1 100644 --- a/src/test/java/ai/chalk/client/TestAggregateBackfillClient.java +++ b/src/test/java/ai/chalk/client/TestAggregateBackfillClient.java @@ -1,16 +1,21 @@ package ai.chalk.client; -import ai.chalk.exceptions.ClientException; +import ai.chalk.exceptions.AggregateBackfillException; import ai.chalk.models.AggregateBackfillParams; import ai.chalk.models.AggregateBackfillResponse; +import ai.chalk.models.AggregateBackfillStatus; +import ai.chalk.models.GetAggregateBackfillJobParams; import ai.chalk.protos.chalk.aggregate.v1.AggregateBackfillJob; import ai.chalk.protos.chalk.aggregate.v1.AggregateServiceGrpc; import ai.chalk.protos.chalk.aggregate.v1.CreateAggregateBackfillV2Request; import ai.chalk.protos.chalk.aggregate.v1.CreateAggregateBackfillV2Response; +import ai.chalk.protos.chalk.aggregate.v1.GetAggregateBackfillJobRequest; +import ai.chalk.protos.chalk.aggregate.v1.GetAggregateBackfillJobResponse; import ai.chalk.protos.chalk.server.v1.AuthServiceGrpc; import ai.chalk.protos.chalk.server.v1.GetTokenRequest; import ai.chalk.protos.chalk.server.v1.GetTokenResponse; import com.google.protobuf.Timestamp; +import com.sun.net.httpserver.Headers; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpServer; import io.grpc.Metadata; @@ -30,13 +35,15 @@ import java.util.List; import java.util.concurrent.atomic.AtomicReference; +import static ai.chalk.protos.chalk.aggregate.v1.AggregateBackfillStatus.AGGREGATE_BACKFILL_STATUS_WORKING; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; /** - * Exercises {@link ChalkClient#triggerAggregateBackfill} through the public client, to check - * that the request reaches the API server's AggregateService with credentials attached. + * Exercises the aggregate backfill methods through both public clients, to check that the + * requests reach the API server's AggregateService with credentials attached. */ public class TestAggregateBackfillClient { private static final String ENVIRONMENT_ID = "test-environment"; @@ -79,6 +86,19 @@ public void createAggregateBackfillV2( .build()); observer.onCompleted(); } + + @Override + public void getAggregateBackfillJob( + GetAggregateBackfillJobRequest request, + StreamObserver observer + ) { + observer.onNext(GetAggregateBackfillJobResponse.newBuilder() + .setJob(AggregateBackfillJob.newBuilder() + .setId(request.getAggregateBackfillId()) + .setStatus(AGGREGATE_BACKFILL_STATUS_WORKING)) + .build()); + observer.onCompleted(); + } }, new ServerInterceptor() { @Override @@ -122,13 +142,26 @@ public ServerCall.Listener interceptCall( .build() ); assertEquals("other-environment", headers.get().get(ENVIRONMENT)); + + ai.chalk.models.AggregateBackfillJob job = client.getAggregateBackfillJob( + GetAggregateBackfillJobParams.builder() + .withAggregateBackfillId("agg-backfill-123") + .withEnvironmentId("other-environment") + .build() + ); + assertEquals("agg-backfill-123", job.getId()); + assertEquals(AggregateBackfillStatus.WORKING, job.getStatus()); + assertEquals("Bearer test-token", headers.get().get(AUTHORIZATION)); + assertEquals("other-environment", headers.get().get(ENVIRONMENT)); } finally { server.shutdownNow(); } } @Test - public void testHttpClientDirectsCallersToTheGrpcClient() throws Exception { + public void testHttpClientCallsTheApiServerOverConnect() throws Exception { + AtomicReference headers = new AtomicReference<>(); + AtomicReference received = new AtomicReference<>(); HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0); server.createContext("/v1/oauth/token", exchange -> respondJson( exchange, @@ -141,6 +174,34 @@ public void testHttpClientDirectsCallersToTheGrpcClient() throws Exception { } """.formatted(ENVIRONMENT_ID) )); + server.createContext("/chalk.aggregate.v1.AggregateService/", exchange -> { + headers.set(exchange.getRequestHeaders()); + byte[] body = exchange.getRequestBody().readAllBytes(); + switch (exchange.getRequestURI().getPath()) { + case "/chalk.aggregate.v1.AggregateService/CreateAggregateBackfillV2" -> { + var request = CreateAggregateBackfillV2Request.parseFrom(body); + if (request.getFeaturesList().contains("user.unknown")) { + respond(exchange, 400, "application/json", + "{\"code\": \"invalid_argument\", \"message\": \"invalid feature\"}"); + return; + } + received.set(request); + respond(exchange, 200, "application/proto", CreateAggregateBackfillV2Response.newBuilder() + .setJob(AggregateBackfillJob.newBuilder().setId("agg-backfill-123")) + .build() + .toByteArray()); + } + case "/chalk.aggregate.v1.AggregateService/GetAggregateBackfillJob" -> respond( + exchange, 200, "application/proto", GetAggregateBackfillJobResponse.newBuilder() + .setJob(AggregateBackfillJob.newBuilder() + .setId(GetAggregateBackfillJobRequest.parseFrom(body).getAggregateBackfillId()) + .setStatus(AGGREGATE_BACKFILL_STATUS_WORKING)) + .build() + .toByteArray() + ); + default -> respond(exchange, 404, "application/json", "{\"code\": \"unimplemented\"}"); + } + }); server.start(); String serverUrl = "http://localhost:" + server.getAddress().getPort(); @@ -151,23 +212,55 @@ public void testHttpClientDirectsCallersToTheGrpcClient() throws Exception { .withClientSecret("test-secret") .withEnvironmentId(ENVIRONMENT_ID) .build()) { + AggregateBackfillResponse response = client.triggerAggregateBackfill( + AggregateBackfillParams.builder().withFeatures("user.spend_30d").build() + ); + assertEquals("agg-backfill-123", response.getJob().getId()); + assertEquals(List.of("user.spend_30d"), received.get().getFeaturesList()); + assertEquals("application/proto", headers.get().getFirst("Content-Type")); + assertEquals("Bearer test-token", headers.get().getFirst("Authorization")); + assertEquals(ENVIRONMENT_ID, headers.get().getFirst("X-Chalk-Env-Id")); + assertEquals("go-api", headers.get().getFirst("X-Chalk-Server")); + assertNull(headers.get().getFirst("X-Chalk-Deployment-Type")); + + ai.chalk.models.AggregateBackfillJob job = client.getAggregateBackfillJob( + GetAggregateBackfillJobParams.builder() + .withAggregateBackfillId("agg-backfill-123") + .withEnvironmentId("other-environment") + .build() + ); + assertEquals("agg-backfill-123", job.getId()); + assertEquals(AggregateBackfillStatus.WORKING, job.getStatus()); + assertEquals("other-environment", headers.get().getFirst("X-Chalk-Env-Id")); + + // Connect errors decode to the same status codes as gRPC, so the shared error + // handling applies. var e = assertThrows( - ClientException.class, + AggregateBackfillException.class, () -> client.triggerAggregateBackfill( - AggregateBackfillParams.builder().withFeatures("user.spend_30d").build() + AggregateBackfillParams.builder().withFeatures("user.unknown").build() ) ); - assertTrue(e.getMessage().contains("only supported by the gRPC client")); + assertEquals("invalid feature", e.getDetail()); } finally { server.stop(0); } } private static void respondJson(HttpExchange exchange, String body) throws IOException { - byte[] response = body.getBytes(StandardCharsets.UTF_8); - exchange.getResponseHeaders().set("Content-Type", "application/json"); - exchange.sendResponseHeaders(200, response.length); - exchange.getResponseBody().write(response); + respond(exchange, 200, "application/json", body); + } + + private static void respond(HttpExchange exchange, int status, String contentType, String body) + throws IOException { + respond(exchange, status, contentType, body.getBytes(StandardCharsets.UTF_8)); + } + + private static void respond(HttpExchange exchange, int status, String contentType, byte[] body) + throws IOException { + exchange.getResponseHeaders().set("Content-Type", contentType); + exchange.sendResponseHeaders(status, body.length); + exchange.getResponseBody().write(body); exchange.close(); } }