Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BEAM-10212] Add caching state client wrapper #15170

Merged
merged 12 commits into from Jul 22, 2021
@@ -0,0 +1,174 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.beam.fn.harness.state;

import com.google.auto.value.AutoValue;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import org.apache.beam.model.fnexecution.v1.BeamFnApi;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.ProcessBundleRequest.CacheToken;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.StateGetResponse;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.StateKey;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.StateKey.IterableSideInput;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.StateKey.MultimapKeysSideInput;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.StateKey.MultimapSideInput;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.StateRequest;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.StateResponse;
import org.apache.beam.vendor.grpc.v1p36p0.com.google.protobuf.ByteString;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.cache.LoadingCache;

/**
* Wraps a delegate BeamFnStateClient and stores the result of state requests in cross bundle cache
* according to the available cache tokens. If there are no cache tokens for the state key requested
* the request is forwarded to the client and executed normally.
*/
public class CachingBeamFnStateClient implements BeamFnStateClient {
anthonyqzhu marked this conversation as resolved.
Show resolved Hide resolved

private final BeamFnStateClient beamFnStateClient;
private final LoadingCache<StateKey, Map<StateCacheKey, StateGetResponse>> stateCache;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It doesn't seem like we are using the Loading part of LoadingCache, did you mean to have the CachingBeamFnStateClient perform the loading?

This would generally be a good thing since requests that go for the same state key could resolve down to a single request to the runner instead of multiple.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this for a future PR

private final Map<CacheToken.SideInput, ByteString> sideInputCacheTokens;
private final ByteString userStateToken;

/**
* Creates a CachingBeamFnStateClient that wraps a BeamFnStateClient with a LoadingCache. Cache
* tokens are sent by the runner to indicate which state is able to be cached.
*/
public CachingBeamFnStateClient(
anthonyqzhu marked this conversation as resolved.
Show resolved Hide resolved
BeamFnStateClient beamFnStateClient,
LoadingCache<StateKey, Map<StateCacheKey, StateGetResponse>> stateCache,
List<CacheToken> cacheTokenList) {
this.beamFnStateClient = beamFnStateClient;
this.stateCache = stateCache;
this.sideInputCacheTokens = new HashMap<>();

// Set up cache tokens.
ByteString tempUserStateToken = ByteString.EMPTY;
for (BeamFnApi.ProcessBundleRequest.CacheToken token : cacheTokenList) {
if (token.hasUserState()) {
tempUserStateToken = token.getToken();
} else if (token.hasSideInput()) {
sideInputCacheTokens.put(token.getSideInput(), token.getToken());
}
}
this.userStateToken = tempUserStateToken;
}

/**
* Completes the response with a cached value if possible, if not forwards the response to the
* BeamFnStateClient and tries caching the result. All Append and Clear requests are forwarded.
*/
@Override
public void handle(
StateRequest.Builder requestBuilder, CompletableFuture<StateResponse> response) {

StateKey stateKey = requestBuilder.getStateKey();
ByteString cacheToken = getCacheToken(stateKey);

// If state is not cacheable proceed as normal.
if (ByteString.EMPTY.equals(cacheToken)) {
beamFnStateClient.handle(requestBuilder, response);
return;
}

switch (requestBuilder.getRequestCase()) {
case GET:
// Check if data is in the cache.
StateCacheKey cacheKey =
StateCacheKey.create(cacheToken, requestBuilder.getGet().getContinuationToken());
Map<StateCacheKey, StateGetResponse> stateKeyMap = stateCache.getUnchecked(stateKey);
StateGetResponse cachedPage = stateKeyMap.get(cacheKey);

// If data is not cached, add callback to add response to cache on completion.
// Otherwise, complete the response with the cached data.
if (cachedPage == null) {
beamFnStateClient.handle(requestBuilder, response);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Question: how is the GET served when cache miss? When cache hits, you have response.complete, do you need the same for cache miss after you put the state into the cache?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The response.complete is executed by the beamFnStateClient.handle call here, but if it is a cache hit we can complete the response immediately so we do not need to forward the request to the delegate state client

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Then can you confirm that after complete, your thenAccept will still be executed? (I am not a async API expert so I am not sure).

CompletableFuture<Void> callback =
response.thenAccept(
stateResponse -> {
stateCache.getUnchecked(stateKey).put(cacheKey, stateResponse.getGet());
});
callback.getNow(null);
anthonyqzhu marked this conversation as resolved.
Show resolved Hide resolved
} else {
response.complete(
StateResponse.newBuilder().setId(requestBuilder.getId()).setGet(cachedPage).build());
}

return;

case APPEND:
// TODO(BEAM-12637): Support APPEND in CachingBeamFnStateClient.
beamFnStateClient.handle(requestBuilder, response);
anthonyqzhu marked this conversation as resolved.
Show resolved Hide resolved
return;

case CLEAR:
// Remove all state key data and replace with an empty response.
beamFnStateClient.handle(requestBuilder, response);
Map<StateCacheKey, StateGetResponse> clearedData = new HashMap<>();
StateCacheKey newKey = StateCacheKey.create(cacheToken, ByteString.EMPTY);
clearedData.put(newKey, StateGetResponse.getDefaultInstance());
stateCache.put(stateKey, clearedData);
return;

default:
throw new IllegalStateException(
String.format("Unknown request type %s", requestBuilder.getRequestCase()));
}
}

private ByteString getCacheToken(BeamFnApi.StateKey stateKey) {
if (stateKey.hasBagUserState()) {
return userStateToken;
} else if (stateKey.hasRunner()) {
// TODO(BEAM-12638): Support caching of remote references.
return ByteString.EMPTY;
} else {
CacheToken.SideInput.Builder sideInputBuilder = CacheToken.SideInput.newBuilder();
if (stateKey.hasIterableSideInput()) {
IterableSideInput iterableSideInput = stateKey.getIterableSideInput();
sideInputBuilder
.setTransformId(iterableSideInput.getTransformId())
.setSideInputId(iterableSideInput.getSideInputId());
} else if (stateKey.hasMultimapSideInput()) {
MultimapSideInput multimapSideInput = stateKey.getMultimapSideInput();
sideInputBuilder
.setTransformId(multimapSideInput.getTransformId())
.setSideInputId(multimapSideInput.getSideInputId());
} else if (stateKey.hasMultimapKeysSideInput()) {
MultimapKeysSideInput multimapKeysSideInput = stateKey.getMultimapKeysSideInput();
sideInputBuilder
.setTransformId(multimapKeysSideInput.getTransformId())
.setSideInputId(multimapKeysSideInput.getSideInputId());
}
return sideInputCacheTokens.getOrDefault(sideInputBuilder.build(), ByteString.EMPTY);
}
}

/** A key for caching the result of a StateGetRequest by cache and continuation tokens. */
@AutoValue
public abstract static class StateCacheKey {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add comments please. Note: every class, public method, and tricky bits of code should have comments. There are some exceptions of course, like getters/setters or trivial self explanatory methods.

If you're curious about learning more, you can refer to Google's public style guide for some good practices: https://google.github.io/styleguide/javaguide.html

public abstract ByteString getCacheToken();

public abstract ByteString getContinuationToken();

static StateCacheKey create(ByteString cacheToken, ByteString continuationToken) {
return new AutoValue_CachingBeamFnStateClient_StateCacheKey(cacheToken, continuationToken);
}
}
}