blob: 281fd16a49fb1e89fe90d078eac86e7eaab82e85 [file] [log] [blame]
Madan Jampani7c521002015-03-23 12:23:01 -07001/*
2 * Copyright 2015 Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Madan Jampanif4c88502016-01-21 12:35:36 -080017package org.onosproject.store.primitives.impl;
Madan Jampani7c521002015-03-23 12:23:01 -070018
Madan Jampanifa242182016-01-22 13:42:54 -080019import static com.google.common.base.Preconditions.checkNotNull;
20import static org.onosproject.store.primitives.impl.StateMachineUpdate.Target.MAP_UPDATE;
21import static org.onosproject.store.primitives.impl.StateMachineUpdate.Target.TX_COMMIT;
22import static org.slf4j.LoggerFactory.getLogger;
Madan Jampani7c521002015-03-23 12:23:01 -070023
Flavio Castro41b1f3a2015-07-31 13:51:32 -070024import java.util.Collection;
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -080025import java.util.Collections;
Flavio Castro41b1f3a2015-07-31 13:51:32 -070026import java.util.Map;
27import java.util.Map.Entry;
28import java.util.Objects;
29import java.util.Set;
30import java.util.concurrent.CompletableFuture;
31import java.util.concurrent.CopyOnWriteArraySet;
32import java.util.concurrent.atomic.AtomicReference;
33import java.util.function.BiFunction;
34import java.util.function.Function;
35import java.util.function.Predicate;
36import java.util.stream.Collectors;
37
Madan Jampanifa242182016-01-22 13:42:54 -080038import org.onlab.util.HexString;
39import org.onlab.util.Match;
40import org.onlab.util.SharedExecutors;
41import org.onlab.util.Tools;
42import org.onosproject.core.ApplicationId;
43import org.onosproject.store.service.AsyncConsistentMap;
44import org.onosproject.store.service.ConsistentMapException;
45import org.onosproject.store.service.ConsistentMapException.ConcurrentModification;
46import org.onosproject.store.service.MapEvent;
47import org.onosproject.store.service.MapEventListener;
48import org.onosproject.store.service.Serializer;
49import org.onosproject.store.service.Versioned;
50import org.slf4j.Logger;
51
52import com.google.common.cache.CacheBuilder;
53import com.google.common.cache.CacheLoader;
54import com.google.common.cache.LoadingCache;
55import com.google.common.collect.Maps;
Madan Jampani7c521002015-03-23 12:23:01 -070056
57/**
58 * AsyncConsistentMap implementation that is backed by a Raft consensus
59 * based database.
60 *
61 * @param <K> type of key.
62 * @param <V> type of value.
63 */
Flavio Castro41b1f3a2015-07-31 13:51:32 -070064public class DefaultAsyncConsistentMap<K, V> implements AsyncConsistentMap<K, V> {
Madan Jampani7c521002015-03-23 12:23:01 -070065
66 private final String name;
Madan Jampanie8af1cc2015-06-23 14:23:31 -070067 private final ApplicationId applicationId;
Madan Jampanif1b8e172015-03-23 11:42:02 -070068 private final Database database;
Madan Jampani7c521002015-03-23 12:23:01 -070069 private final Serializer serializer;
Madan Jampani02b7fb82015-05-01 13:01:20 -070070 private final boolean readOnly;
Madan Jampanie8af1cc2015-06-23 14:23:31 -070071 private final boolean purgeOnUninstall;
Madan Jampani50589ac2015-06-08 11:38:46 -070072
Flavio Castro41b1f3a2015-07-31 13:51:32 -070073 private static final String PRIMITIVE_NAME = "consistentMap";
Flavio Castro5e1f1292015-07-23 17:14:09 -070074 private static final String SIZE = "size";
75 private static final String IS_EMPTY = "isEmpty";
76 private static final String CONTAINS_KEY = "containsKey";
77 private static final String CONTAINS_VALUE = "containsValue";
78 private static final String GET = "get";
79 private static final String COMPUTE_IF = "computeIf";
80 private static final String PUT = "put";
81 private static final String PUT_AND_GET = "putAndGet";
82 private static final String PUT_IF_ABSENT = "putIfAbsent";
83 private static final String REMOVE = "remove";
84 private static final String CLEAR = "clear";
85 private static final String KEY_SET = "keySet";
86 private static final String VALUES = "values";
87 private static final String ENTRY_SET = "entrySet";
88 private static final String REPLACE = "replace";
89 private static final String COMPUTE_IF_ABSENT = "computeIfAbsent";
90
Madan Jampani50589ac2015-06-08 11:38:46 -070091 private final Set<MapEventListener<K, V>> listeners = new CopyOnWriteArraySet<>();
92
93 private final Logger log = getLogger(getClass());
Flavio Castro41b1f3a2015-07-31 13:51:32 -070094 private final MeteringAgent monitor;
Madan Jampani7c521002015-03-23 12:23:01 -070095
96 private static final String ERROR_NULL_KEY = "Key cannot be null";
97 private static final String ERROR_NULL_VALUE = "Null values are not allowed";
98
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -080099 // String representation of serialized byte[] -> original key Object
100 private final LoadingCache<String, K> keyCache = CacheBuilder.newBuilder()
Madan Jampani7c521002015-03-23 12:23:01 -0700101 .softValues()
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800102 .build(new CacheLoader<String, K>() {
Madan Jampani7c521002015-03-23 12:23:01 -0700103
104 @Override
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800105 public K load(String key) {
106 return serializer.decode(HexString.fromHexString(key));
Madan Jampani7c521002015-03-23 12:23:01 -0700107 }
108 });
109
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800110 protected String sK(K key) {
111 String s = HexString.toHexString(serializer.encode(key));
112 keyCache.put(s, key);
113 return s;
114 }
115
Madan Jampani7c521002015-03-23 12:23:01 -0700116 protected K dK(String key) {
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800117 return keyCache.getUnchecked(key);
Madan Jampani7c521002015-03-23 12:23:01 -0700118 }
119
120 public DefaultAsyncConsistentMap(String name,
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700121 ApplicationId applicationId,
122 Database database,
123 Serializer serializer,
124 boolean readOnly,
125 boolean purgeOnUninstall,
126 boolean meteringEnabled) {
Madan Jampani7c521002015-03-23 12:23:01 -0700127 this.name = checkNotNull(name, "map name cannot be null");
Madan Jampanie8af1cc2015-06-23 14:23:31 -0700128 this.applicationId = applicationId;
Madan Jampanif1b8e172015-03-23 11:42:02 -0700129 this.database = checkNotNull(database, "database cannot be null");
Madan Jampani7c521002015-03-23 12:23:01 -0700130 this.serializer = checkNotNull(serializer, "serializer cannot be null");
Madan Jampani02b7fb82015-05-01 13:01:20 -0700131 this.readOnly = readOnly;
Madan Jampanie8af1cc2015-06-23 14:23:31 -0700132 this.purgeOnUninstall = purgeOnUninstall;
Madan Jampani648451f2015-07-21 22:09:05 -0700133 this.database.registerConsumer(update -> {
134 SharedExecutors.getSingleThreadExecutor().execute(() -> {
Madan Jampani9eb55d12015-08-14 07:47:56 -0700135 if (listeners.isEmpty()) {
136 return;
137 }
138 try {
139 if (update.target() == MAP_UPDATE) {
140 Result<UpdateResult<String, byte[]>> result = update.output();
141 if (result.success() && result.value().mapName().equals(name)) {
142 MapEvent<K, V> mapEvent = result.value()
143 .<K, V>map(this::dK,
144 v -> serializer.decode(Tools.copyOf(v)))
145 .toMapEvent();
146 notifyListeners(mapEvent);
147 }
148 } else if (update.target() == TX_COMMIT) {
149 CommitResponse response = update.output();
150 if (response.success()) {
151 response.updates().forEach(u -> {
152 if (u.mapName().equals(name)) {
153 MapEvent<K, V> mapEvent =
154 u.<K, V>map(this::dK,
155 v -> serializer.decode(Tools.copyOf(v)))
156 .toMapEvent();
157 notifyListeners(mapEvent);
158 }
159 });
160 }
Madan Jampani648451f2015-07-21 22:09:05 -0700161 }
Madan Jampani9eb55d12015-08-14 07:47:56 -0700162 } catch (Exception e) {
163 log.warn("Error notifying listeners", e);
Madan Jampani648451f2015-07-21 22:09:05 -0700164 }
165 });
166 });
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700167 this.monitor = new MeteringAgent(PRIMITIVE_NAME, name, meteringEnabled);
Madan Jampani50589ac2015-06-08 11:38:46 -0700168 }
169
170 /**
171 * Returns this map name.
172 * @return map name
173 */
Madan Jampania090a112016-01-18 16:38:17 -0800174 @Override
Madan Jampani50589ac2015-06-08 11:38:46 -0700175 public String name() {
176 return name;
177 }
178
179 /**
180 * Returns the serializer for map entries.
181 * @return map entry serializer
182 */
183 public Serializer serializer() {
184 return serializer;
Madan Jampani7c521002015-03-23 12:23:01 -0700185 }
186
Madan Jampanie8af1cc2015-06-23 14:23:31 -0700187 /**
188 * Returns the applicationId owning this map.
189 * @return application Id
190 */
Madan Jampania090a112016-01-18 16:38:17 -0800191 @Override
Madan Jampanie8af1cc2015-06-23 14:23:31 -0700192 public ApplicationId applicationId() {
193 return applicationId;
194 }
195
196 /**
197 * Returns whether the map entries should be purged when the application
198 * owning it is uninstalled.
199 * @return true is map needs to cleared on app uninstall; false otherwise
200 */
201 public boolean purgeOnUninstall() {
202 return purgeOnUninstall;
203 }
204
Madan Jampani7c521002015-03-23 12:23:01 -0700205 @Override
206 public CompletableFuture<Integer> size() {
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700207 final MeteringAgent.Context timer = monitor.startTimer(SIZE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700208 return database.mapSize(name)
Flavio Castro6e044612015-08-13 14:13:58 -0700209 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700210 }
211
212 @Override
213 public CompletableFuture<Boolean> isEmpty() {
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700214 final MeteringAgent.Context timer = monitor.startTimer(IS_EMPTY);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700215 return database.mapIsEmpty(name)
Flavio Castro6e044612015-08-13 14:13:58 -0700216 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700217 }
218
219 @Override
220 public CompletableFuture<Boolean> containsKey(K key) {
221 checkNotNull(key, ERROR_NULL_KEY);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700222 final MeteringAgent.Context timer = monitor.startTimer(CONTAINS_KEY);
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800223 return database.mapContainsKey(name, sK(key))
Flavio Castro6e044612015-08-13 14:13:58 -0700224 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700225 }
226
227 @Override
228 public CompletableFuture<Boolean> containsValue(V value) {
229 checkNotNull(value, ERROR_NULL_VALUE);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700230 final MeteringAgent.Context timer = monitor.startTimer(CONTAINS_VALUE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700231 return database.mapContainsValue(name, serializer.encode(value))
Flavio Castro6e044612015-08-13 14:13:58 -0700232 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700233 }
234
235 @Override
236 public CompletableFuture<Versioned<V>> get(K key) {
237 checkNotNull(key, ERROR_NULL_KEY);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700238 final MeteringAgent.Context timer = monitor.startTimer(GET);
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800239 return database.mapGet(name, sK(key))
Flavio Castro6e044612015-08-13 14:13:58 -0700240 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700241 .thenApply(v -> v != null ? v.map(serializer::decode) : null);
Madan Jampani7c521002015-03-23 12:23:01 -0700242 }
243
244 @Override
Madan Jampani346d4f52015-05-04 11:09:39 -0700245 public CompletableFuture<Versioned<V>> computeIfAbsent(K key,
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700246 Function<? super K, ? extends V> mappingFunction) {
Madan Jampani7804c992015-07-20 13:20:19 -0700247 checkNotNull(key, ERROR_NULL_KEY);
248 checkNotNull(mappingFunction, "Mapping function cannot be null");
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700249 final MeteringAgent.Context timer = monitor.startTimer(COMPUTE_IF_ABSENT);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700250 return updateAndGet(key, Match.ifNull(), Match.any(), mappingFunction.apply(key))
Flavio Castro6e044612015-08-13 14:13:58 -0700251 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700252 .thenApply(v -> v.newValue());
Madan Jampani346d4f52015-05-04 11:09:39 -0700253 }
254
255 @Override
256 public CompletableFuture<Versioned<V>> computeIfPresent(K key,
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700257 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Madan Jampani346d4f52015-05-04 11:09:39 -0700258 return computeIf(key, Objects::nonNull, remappingFunction);
259 }
260
261 @Override
262 public CompletableFuture<Versioned<V>> compute(K key,
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700263 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Madan Jampani346d4f52015-05-04 11:09:39 -0700264 return computeIf(key, v -> true, remappingFunction);
265 }
266
267 @Override
268 public CompletableFuture<Versioned<V>> computeIf(K key,
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700269 Predicate<? super V> condition,
270 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Madan Jampani346d4f52015-05-04 11:09:39 -0700271 checkNotNull(key, ERROR_NULL_KEY);
272 checkNotNull(condition, "predicate function cannot be null");
273 checkNotNull(remappingFunction, "Remapping function cannot be null");
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700274 final MeteringAgent.Context timer = monitor.startTimer(COMPUTE_IF);
Madan Jampani346d4f52015-05-04 11:09:39 -0700275 return get(key).thenCompose(r1 -> {
276 V existingValue = r1 == null ? null : r1.value();
277 // if the condition evaluates to false, return existing value.
278 if (!condition.test(existingValue)) {
279 return CompletableFuture.completedFuture(r1);
280 }
281
282 AtomicReference<V> computedValue = new AtomicReference<>();
283 // if remappingFunction throws an exception, return the exception.
284 try {
285 computedValue.set(remappingFunction.apply(key, existingValue));
286 } catch (Exception e) {
287 return Tools.exceptionalFuture(e);
288 }
Madan Jampani7804c992015-07-20 13:20:19 -0700289 if (computedValue.get() == null && r1 == null) {
290 return CompletableFuture.completedFuture(null);
Madan Jampani346d4f52015-05-04 11:09:39 -0700291 }
Madan Jampani7804c992015-07-20 13:20:19 -0700292 Match<V> valueMatcher = r1 == null ? Match.ifNull() : Match.any();
293 Match<Long> versionMatcher = r1 == null ? Match.any() : Match.ifValue(r1.version());
294 return updateAndGet(key, valueMatcher, versionMatcher, computedValue.get())
Flavio Castro6e044612015-08-13 14:13:58 -0700295 .whenComplete((r, e) -> timer.stop(e))
Madan Jampani7804c992015-07-20 13:20:19 -0700296 .thenApply(v -> {
297 if (v.updated()) {
298 return v.newValue();
299 } else {
Madan Jampanic7f49f92015-12-10 11:35:06 -0800300 throw new ConcurrentModification("Concurrent update to " + name + " detected");
Madan Jampani7804c992015-07-20 13:20:19 -0700301 }
302 });
303 });
Madan Jampani346d4f52015-05-04 11:09:39 -0700304 }
305
306 @Override
Madan Jampani7c521002015-03-23 12:23:01 -0700307 public CompletableFuture<Versioned<V>> put(K key, V value) {
308 checkNotNull(key, ERROR_NULL_KEY);
309 checkNotNull(value, ERROR_NULL_VALUE);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700310 final MeteringAgent.Context timer = monitor.startTimer(PUT);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700311 return updateAndGet(key, Match.any(), Match.any(), value).thenApply(v -> v.oldValue())
Flavio Castro6e044612015-08-13 14:13:58 -0700312 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani346d4f52015-05-04 11:09:39 -0700313 }
314
315 @Override
316 public CompletableFuture<Versioned<V>> putAndGet(K key, V value) {
317 checkNotNull(key, ERROR_NULL_KEY);
318 checkNotNull(value, ERROR_NULL_VALUE);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700319 final MeteringAgent.Context timer = monitor.startTimer(PUT_AND_GET);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700320 return updateAndGet(key, Match.any(), Match.any(), value).thenApply(v -> v.newValue())
Flavio Castro6e044612015-08-13 14:13:58 -0700321 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700322 }
323
324 @Override
325 public CompletableFuture<Versioned<V>> remove(K key) {
326 checkNotNull(key, ERROR_NULL_KEY);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700327 final MeteringAgent.Context timer = monitor.startTimer(REMOVE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700328 return updateAndGet(key, Match.any(), Match.any(), null).thenApply(v -> v.oldValue())
Flavio Castro6e044612015-08-13 14:13:58 -0700329 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700330 }
331
332 @Override
333 public CompletableFuture<Void> clear() {
Madan Jampani02b7fb82015-05-01 13:01:20 -0700334 checkIfUnmodifiable();
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700335 final MeteringAgent.Context timer = monitor.startTimer(CLEAR);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700336 return database.mapClear(name).thenApply(this::unwrapResult)
Flavio Castro6e044612015-08-13 14:13:58 -0700337 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700338 }
339
340 @Override
341 public CompletableFuture<Set<K>> keySet() {
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700342 final MeteringAgent.Context timer = monitor.startTimer(KEY_SET);
Madan Jampani7804c992015-07-20 13:20:19 -0700343 return database.mapKeySet(name)
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800344 .thenApply(s -> newMappingKeySet(s))
Flavio Castro6e044612015-08-13 14:13:58 -0700345 .whenComplete((r, e) -> timer.stop(e));
Madan Jampani7c521002015-03-23 12:23:01 -0700346 }
347
348 @Override
349 public CompletableFuture<Collection<Versioned<V>>> values() {
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700350 final MeteringAgent.Context timer = monitor.startTimer(VALUES);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700351 return database.mapValues(name)
Flavio Castro6e044612015-08-13 14:13:58 -0700352 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700353 .thenApply(c -> c
354 .stream()
355 .map(v -> v.<V>map(serializer::decode))
356 .collect(Collectors.toList()));
Madan Jampani7c521002015-03-23 12:23:01 -0700357 }
358
359 @Override
360 public CompletableFuture<Set<Entry<K, Versioned<V>>>> entrySet() {
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700361 final MeteringAgent.Context timer = monitor.startTimer(ENTRY_SET);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700362 return database.mapEntrySet(name)
Flavio Castro6e044612015-08-13 14:13:58 -0700363 .whenComplete((r, e) -> timer.stop(e))
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800364 .thenApply(s -> newMappingEntrySet(s));
Madan Jampani7c521002015-03-23 12:23:01 -0700365 }
366
367 @Override
368 public CompletableFuture<Versioned<V>> putIfAbsent(K key, V value) {
369 checkNotNull(key, ERROR_NULL_KEY);
370 checkNotNull(value, ERROR_NULL_VALUE);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700371 final MeteringAgent.Context timer = monitor.startTimer(PUT_IF_ABSENT);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700372 return updateAndGet(key, Match.ifNull(), Match.any(), value)
Flavio Castro6e044612015-08-13 14:13:58 -0700373 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700374 .thenApply(v -> v.oldValue());
Madan Jampani7c521002015-03-23 12:23:01 -0700375 }
376
377 @Override
378 public CompletableFuture<Boolean> remove(K key, V value) {
379 checkNotNull(key, ERROR_NULL_KEY);
380 checkNotNull(value, ERROR_NULL_VALUE);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700381 final MeteringAgent.Context timer = monitor.startTimer(REMOVE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700382 return updateAndGet(key, Match.ifValue(value), Match.any(), null)
Flavio Castro6e044612015-08-13 14:13:58 -0700383 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700384 .thenApply(v -> v.updated());
Madan Jampani7c521002015-03-23 12:23:01 -0700385 }
386
387 @Override
388 public CompletableFuture<Boolean> remove(K key, long version) {
389 checkNotNull(key, ERROR_NULL_KEY);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700390 final MeteringAgent.Context timer = monitor.startTimer(REMOVE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700391 return updateAndGet(key, Match.any(), Match.ifValue(version), null)
Flavio Castro6e044612015-08-13 14:13:58 -0700392 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700393 .thenApply(v -> v.updated());
Madan Jampani7c521002015-03-23 12:23:01 -0700394 }
395
396 @Override
Jihwan Kim9887ad92015-12-12 00:23:57 +0900397 public CompletableFuture<Versioned<V>> replace(K key, V value) {
398 checkNotNull(key, ERROR_NULL_KEY);
399 checkNotNull(value, ERROR_NULL_VALUE);
400 final MeteringAgent.Context timer = monitor.startTimer(REPLACE);
401 return updateAndGet(key, Match.ifNotNull(), Match.any(), value)
402 .whenComplete((r, e) -> timer.stop(e))
403 .thenApply(v -> v.oldValue());
404 }
405
406 @Override
Madan Jampani7c521002015-03-23 12:23:01 -0700407 public CompletableFuture<Boolean> replace(K key, V oldValue, V newValue) {
408 checkNotNull(key, ERROR_NULL_KEY);
Madan Jampani7804c992015-07-20 13:20:19 -0700409 checkNotNull(oldValue, ERROR_NULL_VALUE);
Madan Jampani7c521002015-03-23 12:23:01 -0700410 checkNotNull(newValue, ERROR_NULL_VALUE);
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700411 final MeteringAgent.Context timer = monitor.startTimer(REPLACE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700412 return updateAndGet(key, Match.ifValue(oldValue), Match.any(), newValue)
Flavio Castro6e044612015-08-13 14:13:58 -0700413 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700414 .thenApply(v -> v.updated());
Madan Jampani7c521002015-03-23 12:23:01 -0700415 }
416
417 @Override
418 public CompletableFuture<Boolean> replace(K key, long oldVersion, V newValue) {
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700419 final MeteringAgent.Context timer = monitor.startTimer(REPLACE);
Flavio Castro5e1f1292015-07-23 17:14:09 -0700420 return updateAndGet(key, Match.any(), Match.ifValue(oldVersion), newValue)
Flavio Castro6e044612015-08-13 14:13:58 -0700421 .whenComplete((r, e) -> timer.stop(e))
Flavio Castro5e1f1292015-07-23 17:14:09 -0700422 .thenApply(v -> v.updated());
Madan Jampani346d4f52015-05-04 11:09:39 -0700423 }
424
Madan Jampani14a38da2015-11-16 11:29:00 -0800425 /**
426 * Pre-update hook for performing required checks/actions before going forward with an update operation.
427 * @param key map key.
428 */
429 protected void beforeUpdate(K key) {
430 checkIfUnmodifiable();
431 }
432
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800433 private Set<K> newMappingKeySet(Set<String> s) {
434 return new MappingSet<>(s, Collections::unmodifiableSet,
435 this::sK, this::dK);
436 }
437
438 private Set<Entry<K, Versioned<V>>> newMappingEntrySet(Set<Entry<String, Versioned<byte[]>>> s) {
439 return new MappingSet<>(s, Collections::unmodifiableSet,
440 this::reverseMapRawEntry, this::mapRawEntry);
441 }
442
Madan Jampani7804c992015-07-20 13:20:19 -0700443 private Map.Entry<K, Versioned<V>> mapRawEntry(Map.Entry<String, Versioned<byte[]>> e) {
444 return Maps.immutableEntry(dK(e.getKey()), e.getValue().<V>map(serializer::decode));
445 }
446
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800447 private Map.Entry<String, Versioned<byte[]>> reverseMapRawEntry(Map.Entry<K, Versioned<V>> e) {
448 return Maps.immutableEntry(sK(e.getKey()), e.getValue().map(serializer::encode));
449 }
450
Madan Jampani7804c992015-07-20 13:20:19 -0700451 private CompletableFuture<UpdateResult<K, V>> updateAndGet(K key,
Flavio Castro41b1f3a2015-07-31 13:51:32 -0700452 Match<V> oldValueMatch,
453 Match<Long> oldVersionMatch,
454 V value) {
Madan Jampani14a38da2015-11-16 11:29:00 -0800455 beforeUpdate(key);
Madan Jampani7804c992015-07-20 13:20:19 -0700456 return database.mapUpdate(name,
HIGUCHI Yuta14e865d2015-11-25 20:42:32 -0800457 sK(key),
Flavio Castro5e1f1292015-07-23 17:14:09 -0700458 oldValueMatch.map(serializer::encode),
459 oldVersionMatch,
460 value == null ? null : serializer.encode(value))
Madan Jampani7804c992015-07-20 13:20:19 -0700461 .thenApply(this::unwrapResult)
Madan Jampani85668632015-08-10 10:46:40 -0700462 .thenApply(r -> r.<K, V>map(this::dK, serializer::decode));
Madan Jampani7c521002015-03-23 12:23:01 -0700463 }
Madan Jampanibff6d8f2015-03-31 16:53:47 -0700464
465 private <T> T unwrapResult(Result<T> result) {
466 if (result.status() == Result.Status.LOCKED) {
467 throw new ConsistentMapException.ConcurrentModification();
468 } else if (result.success()) {
469 return result.value();
470 } else {
471 throw new IllegalStateException("Must not be here");
472 }
473 }
Madan Jampani02b7fb82015-05-01 13:01:20 -0700474
475 private void checkIfUnmodifiable() {
476 if (readOnly) {
477 throw new UnsupportedOperationException();
478 }
479 }
Madan Jampani50589ac2015-06-08 11:38:46 -0700480
481 @Override
Madan Jampanidfde6ba2016-01-13 21:36:09 -0800482 public CompletableFuture<Void> addListener(MapEventListener<K, V> listener) {
Madan Jampani50589ac2015-06-08 11:38:46 -0700483 listeners.add(listener);
Madan Jampanidfde6ba2016-01-13 21:36:09 -0800484 return CompletableFuture.completedFuture(null);
Madan Jampani50589ac2015-06-08 11:38:46 -0700485 }
486
487 @Override
Madan Jampanidfde6ba2016-01-13 21:36:09 -0800488 public CompletableFuture<Void> removeListener(MapEventListener<K, V> listener) {
Madan Jampani50589ac2015-06-08 11:38:46 -0700489 listeners.remove(listener);
Madan Jampanidfde6ba2016-01-13 21:36:09 -0800490 return CompletableFuture.completedFuture(null);
Madan Jampani50589ac2015-06-08 11:38:46 -0700491 }
492
493 protected void notifyListeners(MapEvent<K, V> event) {
Madan Jampani85668632015-08-10 10:46:40 -0700494 if (event == null) {
495 return;
496 }
497 listeners.forEach(listener -> {
498 try {
499 listener.event(event);
500 } catch (Exception e) {
501 log.warn("Failure notifying listener about {}", event, e);
Madan Jampani50589ac2015-06-08 11:38:46 -0700502 }
Madan Jampani85668632015-08-10 10:46:40 -0700503 });
Madan Jampani50589ac2015-06-08 11:38:46 -0700504 }
Madan Jampanibab51a42015-08-10 13:53:35 -0700505}