/
MongoThingsSearchPersistence.java
240 lines (205 loc) · 10.4 KB
/
MongoThingsSearchPersistence.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
/*
* Copyright (c) 2017 Bosch Software Innovations GmbH.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/org/documents/epl-2.0/index.php
*
* Contributors:
* Bosch Software Innovations GmbH - initial contribution
*/
package org.eclipse.ditto.services.thingsearch.persistence.read;
import static com.mongodb.client.model.Filters.and;
import static org.eclipse.ditto.model.base.common.ConditionChecker.checkNotNull;
import static org.eclipse.ditto.services.thingsearch.persistence.PersistenceConstants.FIELD_DELETED;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
import org.bson.BsonDocument;
import org.bson.BsonNull;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.eclipse.ditto.services.models.thingsearch.SearchNamespaceReportResult;
import org.eclipse.ditto.services.models.thingsearch.SearchNamespaceResultEntry;
import org.eclipse.ditto.services.thingsearch.common.model.ResultList;
import org.eclipse.ditto.services.thingsearch.common.model.ResultListImpl;
import org.eclipse.ditto.services.thingsearch.persistence.Indices;
import org.eclipse.ditto.services.thingsearch.persistence.PersistenceConstants;
import org.eclipse.ditto.services.thingsearch.persistence.read.criteria.visitors.CreateBsonVisitor;
import org.eclipse.ditto.services.thingsearch.persistence.read.query.MongoQuery;
import org.eclipse.ditto.services.thingsearch.querymodel.query.PolicyRestrictedSearchAggregation;
import org.eclipse.ditto.services.thingsearch.querymodel.query.Query;
import org.eclipse.ditto.services.utils.config.MongoConfig;
import org.eclipse.ditto.services.utils.persistence.mongo.MongoClientWrapper;
import org.eclipse.ditto.services.utils.persistence.mongo.indices.IndexInitializer;
import org.eclipse.ditto.signals.commands.base.exceptions.GatewayQueryTimeExceededException;
import com.mongodb.MongoExecutionTimeoutException;
import com.mongodb.client.model.CountOptions;
import com.mongodb.reactivestreams.client.AggregatePublisher;
import com.mongodb.reactivestreams.client.MongoCollection;
import akka.NotUsed;
import akka.actor.ActorSystem;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import akka.japi.pf.PFBuilder;
import akka.stream.ActorMaterializer;
import akka.stream.javadsl.Source;
import scala.PartialFunction;
/**
* Persistence Service Implementation for asynchronous MongoDB search.
*/
public class MongoThingsSearchPersistence implements ThingsSearchPersistence {
/**
* Filter for not-deleted entries.
*/
public static final BsonDocument FILTER_NOT_DELETED = new BsonDocument().append(FIELD_DELETED, BsonNull.VALUE);
private final MongoCollection<Document> collection;
private final LoggingAdapter log;
private final ActorMaterializer materializer;
private final IndexInitializer indexInitializer;
private final Duration maxQueryTime;
/**
* Initializes the things search persistence with a passed in {@code persistence}.
*
* @param clientWrapper the mongoDB persistence wrapper.
* @param actorSystem the Akka ActorSystem.
*/
public MongoThingsSearchPersistence(final MongoClientWrapper clientWrapper, final ActorSystem actorSystem) {
collection = clientWrapper.getDatabase().getCollection(PersistenceConstants.THINGS_COLLECTION_NAME);
log = Logging.getLogger(actorSystem, getClass());
materializer = ActorMaterializer.create(actorSystem);
indexInitializer = IndexInitializer.of(clientWrapper.getDatabase(), materializer);
maxQueryTime = MongoConfig.getMaxQueryTime(actorSystem.settings().config());
}
@Override
public CompletionStage<Void> initializeIndices() {
return indexInitializer.initialize(PersistenceConstants.THINGS_COLLECTION_NAME, Indices.Things.all());
}
@Override
public Source<SearchNamespaceReportResult, NotUsed> generateNamespaceCountReport() {
final AggregatePublisher<Document> aggregatePublisher = collection.aggregate(
Collections.singletonList(
new Document("$group",
new Document(PersistenceConstants.FIELD_ID, "$_namespace")
.append(PersistenceConstants.FIELD_COUNT, new Document("$sum", 1))
)
)
);
return Source.fromPublisher(aggregatePublisher)
.map(document -> {
final String namespace = (document.get(PersistenceConstants.FIELD_ID) != null)
? document.get(PersistenceConstants.FIELD_ID).toString()
: "NOT_MIGRATED";
final long count = Long.parseLong(document.get(PersistenceConstants.FIELD_COUNT).toString());
return new SearchNamespaceResultEntry(namespace, count);
})
.fold(new ArrayList<SearchNamespaceResultEntry>(), (list, entry) -> {
list.add(entry);
return list;
})
.map(SearchNamespaceReportResult::new);
}
@Override
public Source<Long, NotUsed> count(final PolicyRestrictedSearchAggregation policyRestrictedSearchAggregation) {
checkNotNull(policyRestrictedSearchAggregation, "policy restricted aggregation");
final Source<Document, NotUsed> source = policyRestrictedSearchAggregation.execute(collection, maxQueryTime);
return source.map(doc -> doc.get(PersistenceConstants.COUNT_RESULT_NAME))
.map(countResult -> (Number) countResult)
.map(Number::longValue) // use Number.longValue() to support both Integer and Long values
.orElse(Source.single(0L))
.mapError(handleMongoExecutionTimeExceededException())
.log("count");
}
@Override
public Source<ResultList<String>, NotUsed> findAll(final PolicyRestrictedSearchAggregation aggregation) {
checkNotNull(aggregation, "aggregation");
final Source<Document, NotUsed> source = aggregation.execute(collection, maxQueryTime);
return source.map(doc -> doc.getString(PersistenceConstants.FIELD_ID))
.fold(new ArrayList<String>(), (list, id) -> {
list.add(id);
return list;
})
.map(resultsPlus0ne -> toResultList(resultsPlus0ne, aggregation.getSkip(), aggregation.getLimit()))
.mapError(handleMongoExecutionTimeExceededException())
.log("findAll");
}
@Override
public Source<Long, NotUsed> count(final Query query) {
checkNotNull(query, "query");
final BsonDocument queryFilter = getMongoFilter(query);
log.debug("count with query filter <{}>.", queryFilter);
final Bson filter = and(FILTER_NOT_DELETED, queryFilter);
final CountOptions countOptions = new CountOptions()
.skip(query.getSkip())
.limit(query.getLimit())
.maxTime(maxQueryTime.getSeconds(), TimeUnit.SECONDS);
return Source.fromPublisher(collection.count(filter, countOptions))
.mapError(handleMongoExecutionTimeExceededException())
.log("count");
}
@Override
public Source<ResultList<String>, NotUsed> findAll(final Query query) {
checkNotNull(query, "query");
final BsonDocument queryFilter = getMongoFilter(query);
if (log.isDebugEnabled()) {
log.debug("findAll with query filter <{}>.", queryFilter);
}
final Bson filter = and(FILTER_NOT_DELETED, queryFilter);
final Optional<Bson> sortOptions = Optional.of(getMongoSort(query));
final int limit = query.getLimit();
final int skip = query.getSkip();
final Bson projection = new Document(PersistenceConstants.FIELD_ID, 1);
return Source.fromPublisher(collection.find(filter, Document.class)
.sort(sortOptions.orElse(null))
.limit(limit + 1)
.skip(skip)
.projection(projection)
.maxTime(maxQueryTime.getSeconds(), TimeUnit.SECONDS)
)
.map(doc -> doc.getString(PersistenceConstants.FIELD_ID))
.fold(new ArrayList<String>(), (list, id) -> {
list.add(id);
return list;
})
.map(resultsPlus0ne -> toResultList(resultsPlus0ne, skip, limit))
.mapError(handleMongoExecutionTimeExceededException())
.log("findAll");
}
private ResultList<String> toResultList(final List<String> resultsPlus0ne, final int skip, final int limit) {
log.debug("Creating paged ResultList from parameters: resultsPlusOne=<{}>,skip={},limit={}",
resultsPlus0ne, skip, limit);
final ResultList<String> pagedResultList;
if (resultsPlus0ne.size() <= limit) {
pagedResultList = new ResultListImpl<>(resultsPlus0ne, ResultList.NO_NEXT_PAGE);
} else {
// MongoDB returned limit + 1 items. However only <limit> items are of interest per page.
resultsPlus0ne.remove(limit);
final long nextPageOffset = (long) skip + limit;
pagedResultList = new ResultListImpl<>(resultsPlus0ne, nextPageOffset);
}
log.debug("Returning paged ResultList: {}", pagedResultList);
return pagedResultList;
}
private static BsonDocument getMongoFilter(final Query query) {
return org.eclipse.ditto.services.utils.persistence.mongo.BsonUtil.toBsonDocument(
CreateBsonVisitor.apply(query.getCriteria()));
}
private static Bson getMongoSort(final Query query) {
final MongoQuery mongoQuery = (MongoQuery) query;
return mongoQuery.getSortOptionsAsBson();
}
private PartialFunction<Throwable, Throwable> handleMongoExecutionTimeExceededException() {
return new PFBuilder<Throwable, Throwable>()
.match(Throwable.class, error ->
error instanceof MongoExecutionTimeoutException
? GatewayQueryTimeExceededException.newBuilder().build()
: error
)
.build();
}
}