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

add redis implementation, add support for multiple cache providers #57

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions handler/core/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ dependencies {
implementation(group = "io.vertx", name = "vertx-core")
implementation(group = "io.vertx", name = "vertx-service-proxy")
implementation(group = "io.vertx", name = "vertx-rx-java2")
implementation(group = "io.vertx", name = "vertx-redis-client")
implementation(group = "org.apache.commons", name = "commons-lang3")
implementation(group = "com.google.guava", name = "guava")

Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* Copyright (C) 2019 Knot.x Project
*
* 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 io.knotx.fragments.handler.action.cache;

import io.reactivex.Maybe;

public interface Cache {

Maybe<Object> get(String key);

void put(String key, Object value);

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
/*
* Copyright (C) 2019 Knot.x Project
*
* 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 io.knotx.fragments.handler.action.cache;

import io.knotx.fragments.api.Fragment;
import io.knotx.fragments.handler.api.Action;
import io.knotx.fragments.handler.api.domain.FragmentContext;
import io.knotx.fragments.handler.api.domain.FragmentResult;
import io.knotx.server.api.context.ClientRequest;
import io.knotx.server.common.placeholders.PlaceholdersResolver;
import io.knotx.server.common.placeholders.SourceDefinitions;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import org.apache.commons.lang3.StringUtils;

public class CacheAction implements Action {

private static final Logger LOGGER = LoggerFactory.getLogger(CacheAction.class);

private final Action doAction;

private final String payloadKey;

private final JsonObject config;

private final Cache cache;

public CacheAction(Action doAction, JsonObject config,
Cache cache) {
this.doAction = doAction;
this.config = config;
this.payloadKey = getPayloadKey(config);
this.cache = cache;
}

@Override
public void apply(FragmentContext fragmentContext, Handler<AsyncResult<FragmentResult>> resultHandler) {
String cacheKey = getCacheKey(config, fragmentContext.getClientRequest());
cache.get(cacheKey)
.subscribe(cachedValue -> {
LOGGER.trace("Cache responsed with value: {}", cachedValue);
Fragment fragment = fragmentContext.getFragment();
fragment.appendPayload(payloadKey, cachedValue);
FragmentResult result = new FragmentResult(fragment, FragmentResult.SUCCESS_TRANSITION);
Future.succeededFuture(result)
.setHandler(resultHandler);
}, error -> {
LOGGER.error("Could not fetch data from cache. {}", error);
Fragment fragment = fragmentContext.getFragment();
FragmentResult result = new FragmentResult(fragment, FragmentResult.ERROR_TRANSITION);
Future.succeededFuture(result)
.setHandler(resultHandler);
Copy link
Contributor

@marcinus marcinus Mar 26, 2020

Choose a reason for hiding this comment

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

Consider if this should be configurable? Should cache failure always mean general failure, or perhaps just some throttling would be acceptable?

}, () -> {
LOGGER.trace("Cache didn't return value.");
callDoActionAndCache(fragmentContext, resultHandler, cacheKey);
});
}

private void callDoActionAndCache(FragmentContext fragmentContext,
Handler<AsyncResult<FragmentResult>> resultHandler, String cacheKey) {
doAction.apply(fragmentContext, asyncResult -> {
Copy link
Contributor

Choose a reason for hiding this comment

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

Change to rxified Action interface

if (asyncResult.succeeded()) {
FragmentResult fragmentResult = asyncResult.result();
if (FragmentResult.SUCCESS_TRANSITION.equals(fragmentResult.getTransition())
&& fragmentResult.getFragment()
.getPayload()
.containsKey(payloadKey)) {
JsonObject resultPayload = fragmentResult.getFragment()
.getPayload();
cache.put(cacheKey, resultPayload.getMap()
.get(payloadKey));
}
Future.succeededFuture(fragmentResult)
Copy link
Contributor

Choose a reason for hiding this comment

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

consider whether this should be configurable

Copy link
Contributor

Choose a reason for hiding this comment

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

what if doAction specifies a _fallback transition, but there is something that could be cached?
In general: what is the approach for handling decorated actions' results/transitions

.setHandler(resultHandler);
} else {
Future.<FragmentResult>failedFuture(asyncResult.cause()).setHandler(resultHandler);
}
});
}

private static String getPayloadKey(JsonObject config) {
String result = config.getString("payloadKey");
if (StringUtils.isBlank(result)) {
throw new IllegalArgumentException(
"Action requires payloadKey value in configuration.");
}
return result;
}

private static String getCacheKey(JsonObject config, ClientRequest clientRequest) {
String key = config.getString("cacheKey");
if (StringUtils.isBlank(key)) {
throw new IllegalArgumentException("Action requires cacheKey value in configuration.");
}
return PlaceholdersResolver.resolve(key, buildSourceDefinitions(clientRequest));
}

private static SourceDefinitions buildSourceDefinitions(ClientRequest clientRequest) {
return SourceDefinitions.builder()
.addClientRequestSource(clientRequest)
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* Copyright (C) 2019 Knot.x Project
*
* 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 io.knotx.fragments.handler.action.cache;


import io.reactivex.Maybe;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

import com.google.common.cache.CacheBuilder;

import io.vertx.core.json.JsonObject;

public class InMemoryCache implements Cache {

private static final long DEFAULT_MAXIMUM_SIZE = 1000;
private static final long DEFAULT_TTL = 5000;

private final com.google.common.cache.Cache cache;

public InMemoryCache(JsonObject config) {
cache = createCache(config);
}

@Override
public Maybe<Object> get(String key) {
return Optional.ofNullable(cache.getIfPresent(key))
.map(Maybe::just)
.orElse(Maybe.empty());
}

@Override
public void put(String key, Object value) {
cache.put(key, value);
}

private static com.google.common.cache.Cache createCache(JsonObject config) {
JsonObject cache = config.getJsonObject("cache");
long maxSize =
cache == null ? DEFAULT_MAXIMUM_SIZE : cache.getLong("maximumSize", DEFAULT_MAXIMUM_SIZE);
long ttl = cache == null ? DEFAULT_TTL : cache.getLong("ttl", DEFAULT_TTL);
return CacheBuilder.newBuilder()
.maximumSize(maxSize)
.expireAfterWrite(ttl, TimeUnit.MILLISECONDS)
.build();
}
}
Loading