Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 37 additions & 12 deletions src/main/java/ai/chalk/client/AggregateBackfills.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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.
*
* <p> A single CreateAggregateBackfillV2 call plans and creates every job server-side.
Expand All @@ -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);
}
Expand All @@ -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 {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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<String> queryTags = params.getQueryTags() == null ? List.of() : params.getQueryTags();

var userParams = AggregateBackfillUserParams.newBuilder()
Expand All @@ -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) {
Expand Down Expand Up @@ -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<ServerError> errors = new ArrayList<>();
for (var error : createResponse.getErrorsList()) {
Expand All @@ -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
Expand Down
24 changes: 24 additions & 0 deletions src/main/java/ai/chalk/client/AggregateRpc.java
Original file line number Diff line number Diff line change
@@ -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 {
<ReqT, RespT> RespT call(MethodDescriptor<ReqT, RespT> method, ReqT request) throws ChalkException;

static AggregateRpc grpc(AbstractStub<?> stub) {
return new AggregateRpc() {
@Override
public <ReqT, RespT> RespT call(MethodDescriptor<ReqT, RespT> method, ReqT request) {
return ClientCalls.blockingUnaryCall(stub.getChannel(), method, stub.getCallOptions(), request);
}
};
}
}
34 changes: 25 additions & 9 deletions src/main/java/ai/chalk/client/ChalkClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -296,8 +296,6 @@ default DeleteFeaturesResult deleteFeatures(DeleteFeaturesParams params) throws
* operation as the {@code chalk aggregate backfill} CLI command.
* <p> See {@link AggregateBackfillParams} for more details on the parameters.
*
* <p> This is supported only by the gRPC client; see {@link ChalkClient#createGrpc()}.
*
* <p>
* Example usage:
* <pre>
Expand Down Expand Up @@ -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}.
*
* <p>
* Example usage:
* <pre>
* {@code
* AggregateBackfillJob job = client.getAggregateBackfillJob(
* GetAggregateBackfillJobParams.builder()
* .withAggregateBackfillId(backfillId)
* .build()
* );
* AggregateBackfillStatus status = job.getStatus();
* }
* </pre>
* </p>
*
* @return {@link AggregateBackfillJob}, or null if the server returns no job
*/
AggregateBackfillJob getAggregateBackfillJob(GetAggregateBackfillJobParams params)
throws ChalkException;



Expand Down
90 changes: 90 additions & 0 deletions src/main/java/ai/chalk/client/ChalkClientImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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<String, String> 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();
Expand Down Expand Up @@ -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 <ReqT, RespT> RespT call(MethodDescriptor<ReqT, RespT> 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<byte[]> 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<byte[]> 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();
}
}
20 changes: 16 additions & 4 deletions src/main/java/ai/chalk/client/GRPCClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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))
);
}

Expand Down
7 changes: 6 additions & 1 deletion src/main/java/ai/chalk/internal/request/RequestHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -166,6 +167,10 @@ public HttpResponse<byte[]> 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) {
Expand Down Expand Up @@ -223,7 +228,7 @@ public HttpResponse<byte[]> sendRequest(SendRequestParams args) throws ChalkExce
}
}

if (response.statusCode() != 200) {
if (response.statusCode() != 200 && !args.isReturnErrorResponses()) {
throw getHttpException(response, request.uri().toString());
}

Expand Down
Loading
Loading