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 da00fc4..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,20 +327,13 @@ 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}.
*
- * This is supported only by the gRPC client; see {@link ChalkClient#createGrpc()}.
- *
*
* Example usage:
*
@@ -359,13 +350,8 @@ default AggregateBackfillResponse triggerAggregateBackfill(AggregateBackfillPara
*
* @return {@link AggregateBackfillJob}, or null if the server returns no job
*/
- default AggregateBackfillJob getAggregateBackfillJob(GetAggregateBackfillJobParams params)
- throws ChalkException {
- throw new ClientException(
- "getAggregateBackfillJob is only supported by the gRPC client. Build one with "
- + "ChalkClient.builder().withGrpc().build() or ChalkClient.createGrpc()."
- );
- }
+ 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 ab42582..418f1e3 100644
--- a/src/main/java/ai/chalk/client/GRPCClient.java
+++ b/src/main/java/ai/chalk/client/GRPCClient.java
@@ -17,7 +17,6 @@
import ai.chalk.models.UploadFeaturesParams;
import ai.chalk.models.UploadFeaturesResult;
import ai.chalk.protos.chalk.aggregate.v1.AggregateServiceGrpc;
-import ai.chalk.protos.chalk.aggregate.v1.GetAggregateBackfillJobRequest;
import ai.chalk.protos.chalk.common.v1.*;
import ai.chalk.protos.chalk.engine.v1.PingRequest;
import ai.chalk.protos.chalk.engine.v1.QueryServiceGrpc;
@@ -798,29 +797,21 @@ 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 {
- if (params.getAggregateBackfillId() == null || params.getAggregateBackfillId().isEmpty()) {
- throw new ClientException("aggregateBackfillId is required to get an aggregate backfill job.");
- }
- var response = this.stubsProvider.getAggregateStub(Optional.ofNullable(params.getTimeout()))
- .withInterceptors(this.getRequestHeaderInterceptor(params.getEnvironmentId(), null))
- .getAggregateBackfillJob(
- 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;
+ 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))
+ );
}
@Override
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/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 8e35295..2a8b5b1 100644
--- a/src/test/java/ai/chalk/client/TestAggregateBackfillClient.java
+++ b/src/test/java/ai/chalk/client/TestAggregateBackfillClient.java
@@ -1,6 +1,6 @@
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;
@@ -15,6 +15,7 @@
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;
@@ -36,12 +37,13 @@
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";
@@ -157,7 +159,9 @@ public ServerCall.Listener interceptCall(
}
@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,
@@ -170,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();
@@ -180,31 +212,55 @@ public void testHttpClientDirectsCallersToTheGrpcClient() throws Exception {
.withClientSecret("test-secret")
.withEnvironmentId(ENVIRONMENT_ID)
.build()) {
- var e = assertThrows(
- ClientException.class,
- () -> client.triggerAggregateBackfill(
- AggregateBackfillParams.builder().withFeatures("user.spend_30d").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()
);
- assertTrue(e.getMessage().contains("only supported by the gRPC client"));
+ assertEquals("agg-backfill-123", job.getId());
+ assertEquals(AggregateBackfillStatus.WORKING, job.getStatus());
+ assertEquals("other-environment", headers.get().getFirst("X-Chalk-Env-Id"));
- var getError = assertThrows(
- ClientException.class,
- () -> client.getAggregateBackfillJob(
- GetAggregateBackfillJobParams.builder().withAggregateBackfillId("agg-backfill-123").build()
+ // Connect errors decode to the same status codes as gRPC, so the shared error
+ // handling applies.
+ var e = assertThrows(
+ AggregateBackfillException.class,
+ () -> client.triggerAggregateBackfill(
+ AggregateBackfillParams.builder().withFeatures("user.unknown").build()
)
);
- assertTrue(getError.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();
}
}