• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

knowledgepixels / nanopub-registry / 22572052718

02 Mar 2026 10:33AM UTC coverage: 25.19% (+0.1%) from 25.064%
22572052718

push

github

ashleycaselli
chore(logging): add logging messages for MongoDB index initialization and element retrieval

125 of 586 branches covered (21.33%)

Branch coverage included in aggregate %.

471 of 1780 relevant lines covered (26.46%)

4.83 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

58.78
src/main/java/com/knowledgepixels/registry/RegistryDB.java
1
package com.knowledgepixels.registry;
2

3
import com.knowledgepixels.registry.db.IndexInitializer;
4
import com.mongodb.MongoClient;
5
import com.mongodb.MongoNamespace;
6
import com.mongodb.MongoWriteException;
7
import com.mongodb.ServerAddress;
8
import com.mongodb.client.ClientSession;
9
import com.mongodb.client.MongoCollection;
10
import com.mongodb.client.MongoCursor;
11
import com.mongodb.client.MongoDatabase;
12
import com.mongodb.client.model.CountOptions;
13
import com.mongodb.client.model.UpdateOptions;
14
import net.trustyuri.TrustyUriUtils;
15
import org.bson.Document;
16
import org.bson.conversions.Bson;
17
import org.bson.types.Binary;
18
import org.eclipse.rdf4j.common.exception.RDF4JException;
19
import org.eclipse.rdf4j.model.IRI;
20
import org.eclipse.rdf4j.rio.RDFFormat;
21
import org.nanopub.MalformedNanopubException;
22
import org.nanopub.Nanopub;
23
import org.nanopub.NanopubUtils;
24
import org.nanopub.extra.security.MalformedCryptoElementException;
25
import org.nanopub.extra.security.NanopubSignatureElement;
26
import org.nanopub.extra.security.SignatureUtils;
27
import org.nanopub.jelly.JellyUtils;
28
import org.slf4j.Logger;
29
import org.slf4j.LoggerFactory;
30

31
import java.io.IOException;
32
import java.security.GeneralSecurityException;
33
import java.util.ArrayList;
34

35
import static com.mongodb.client.model.Indexes.ascending;
36

37
public class RegistryDB {
38

39
    private RegistryDB() {
40
    }
41

42
    private static final String REGISTRY_DB_NAME = Utils.getEnv("REGISTRY_DB_NAME", "nanopubRegistry");
12✔
43

44
    private static final Logger logger = LoggerFactory.getLogger(RegistryDB.class);
9✔
45

46
    private static MongoClient mongoClient;
47
    private static MongoDatabase mongoDB;
48

49
    /**
50
     * Returns the MongoDB database instance.
51
     *
52
     * @return the MongoDatabase instance
53
     */
54
    public static MongoDatabase getDB() {
55
        return mongoDB;
6✔
56
    }
57

58
    /**
59
     * Returns the MongoDB client instance.
60
     *
61
     * @return the MongoClient instance
62
     */
63
    public static MongoClient getClient() {
64
        return mongoClient;
6✔
65
    }
66

67
    /**
68
     * Returns the specified collection from the MongoDB database.
69
     *
70
     * @param name the name of the collection
71
     * @return the MongoCollection instance
72
     */
73
    public static MongoCollection<Document> collection(String name) {
74
        return mongoDB.getCollection(name);
12✔
75
    }
76

77
    /**
78
     * Initializes the MongoDB connection and sets up collections and indexes if not already initialized.
79
     */
80
    public static void init() {
81
        if (mongoClient != null) {
6✔
82
            logger.info("RegistryDB already initialized");
9✔
83
            return;
3✔
84
        }
85
        final String REGISTRY_DB_HOST = Utils.getEnv("REGISTRY_DB_HOST", "mongodb");
12✔
86
        final int REGISTRY_DB_PORT = Integer.parseInt(Utils.getEnv("REGISTRY_DB_PORT", String.valueOf(ServerAddress.defaultPort())));
18✔
87
        logger.info("Initializing RegistryDB connection to database '{}' at {}:{}", REGISTRY_DB_NAME, REGISTRY_DB_HOST, REGISTRY_DB_PORT);
54✔
88
        mongoClient = new MongoClient(REGISTRY_DB_HOST, REGISTRY_DB_PORT);
18✔
89
        mongoDB = mongoClient.getDatabase(REGISTRY_DB_NAME);
12✔
90

91
        try (ClientSession mongoSession = mongoClient.startSession()) {
9✔
92
            if (isInitialized(mongoSession)) {
9!
93
                return;
×
94
            }
95
            IndexInitializer.initCollections(mongoSession);
6✔
96
        }
×
97
    }
3✔
98

99
    /**
100
     * Checks if the database has been initialized.
101
     *
102
     * @param mongoSession the MongoDB client session
103
     * @return true if initialized, false otherwise
104
     */
105
    public static boolean isInitialized(ClientSession mongoSession) {
106
        return getValue(mongoSession, Collection.SERVER_INFO.toString(), "setupId") != null;
24!
107
    }
108

109
    /**
110
     * Renames a collection in the database. If the new collection name already exists, it will be dropped first.
111
     *
112
     * @param oldCollectionName the current name of the collection
113
     * @param newCollectionName the new name for the collection
114
     */
115
    public static void rename(String oldCollectionName, String newCollectionName) {
116
        // Designed as idempotent operation: calling multiple times has same effect as calling once
117
        if (hasCollection(oldCollectionName)) {
9✔
118
            if (hasCollection(newCollectionName)) {
9✔
119
                collection(newCollectionName).drop();
9✔
120
            }
121
            collection(oldCollectionName).renameCollection(new MongoNamespace(REGISTRY_DB_NAME, newCollectionName));
24✔
122
        }
123
    }
3✔
124

125
    /**
126
     * Checks if a collection with the given name exists in the database.
127
     *
128
     * @param collectionName the name of the collection to check
129
     * @return true if the collection exists, false otherwise
130
     */
131
    public static boolean hasCollection(String collectionName) {
132
        return mongoDB.listCollectionNames().into(new ArrayList<>()).contains(collectionName);
30✔
133
    }
134

135
    /**
136
     * Increases the trust state counter in the server info collection.
137
     *
138
     * @param mongoSession the MongoDB client session
139
     */
140
    public static void increaseStateCounter(ClientSession mongoSession) {
141
        MongoCursor<Document> cursor = collection(Collection.SERVER_INFO.toString()).find(mongoSession, new Document("_id", "trustStateCounter")).cursor();
36✔
142
        if (cursor.hasNext()) {
9✔
143
            long counter = cursor.next().getLong("value");
21✔
144
            collection(Collection.SERVER_INFO.toString()).updateOne(mongoSession, new Document("_id", "trustStateCounter"), new Document("$set", new Document("value", counter + 1)));
69✔
145
        } else {
3✔
146
            collection(Collection.SERVER_INFO.toString()).insertOne(mongoSession, new Document("_id", "trustStateCounter").append("value", 0L));
42✔
147
        }
148
    }
3✔
149

150
    /**
151
     * Checks if an element with the given name exists in the specified collection.
152
     *
153
     * @param mongoSession the MongoDB client session
154
     * @param collection   the name of the collection
155
     * @param elementName  the name of the element used as the _id field
156
     * @return true if the element exists, false otherwise
157
     */
158
    public static boolean has(ClientSession mongoSession, String collection, String elementName) {
159
        return has(mongoSession, collection, new Document("_id", elementName));
27✔
160
    }
161

162
    private static final CountOptions hasCountOptions = new CountOptions().limit(1);
21✔
163

164
    /**
165
     * Checks if any document matching the given filter exists in the specified collection.
166
     *
167
     * @param mongoSession the MongoDB client session
168
     * @param collection   the name of the collection
169
     * @param find         the filter to match documents
170
     * @return true if at least one matching document exists, false otherwise
171
     */
172
    public static boolean has(ClientSession mongoSession, String collection, Bson find) {
173
        return collection(collection).countDocuments(mongoSession, find, hasCountOptions) > 0;
39✔
174
    }
175

176
    /**
177
     * Retrieves a cursor for documents matching the given filter in the specified collection.
178
     *
179
     * @param mongoSession the MongoDB client session
180
     * @param collection   the name of the collection
181
     * @param find         the filter to match documents
182
     * @return a MongoCursor for the matching documents
183
     */
184
    public static MongoCursor<Document> get(ClientSession mongoSession, String collection, Bson find) {
185
        return collection(collection).find(mongoSession, find).cursor();
21✔
186
    }
187

188
    /**
189
     * Retrieves the value of an element with the given name from the specified collection.
190
     *
191
     * @param mongoSession the MongoDB client session
192
     * @param collection   the name of the collection
193
     * @param elementName  the name of the element used as the _id field
194
     * @return the value of the element, or null if not found
195
     */
196
    public static Object getValue(ClientSession mongoSession, String collection, String elementName) {
197
        logger.info("Getting value of element '{}' from collection '{}'", elementName, collection);
15✔
198
        Document d = collection(collection).find(mongoSession, new Document("_id", elementName)).first();
36✔
199
        if (d == null) {
6✔
200
            return null;
6✔
201
        }
202
        return d.get("value");
12✔
203
    }
204

205
    /**
206
     * Retrieves the boolean value of an element with the given name from the specified collection.
207
     *
208
     * @param mongoSession the MongoDB client session
209
     * @param collection   the name of the collection
210
     * @param elementName  the name of the element used as the _id field
211
     * @return the value of the element, or null if not found
212
     */
213
    public static boolean isSet(ClientSession mongoSession, String collection, String elementName) {
214
        Document d = collection(collection).find(mongoSession, new Document("_id", elementName)).first();
36✔
215
        if (d == null) {
6✔
216
            return false;
6✔
217
        }
218
        return d.getBoolean("value");
15✔
219
    }
220

221
    /**
222
     * Retrieves a single document matching the given filter from the specified collection.
223
     *
224
     * @param mongoSession the MongoDB client session
225
     * @param collection   the name of the collection
226
     * @param find         the filter to match the document
227
     * @return the matching document, or null if not found
228
     */
229
    public static Document getOne(ClientSession mongoSession, String collection, Bson find) {
230
        return collection(collection).find(mongoSession, find).first();
24✔
231
    }
232

233
    /**
234
     * Retrieves the maximum value of a specified field from the documents in the given collection.
235
     *
236
     * @param mongoSession the MongoDB client session
237
     * @param collection   the name of the collection
238
     * @param fieldName    the field for which to find the maximum value
239
     * @return the maximum value of the specified field, or null if no documents exist
240
     */
241
    public static Object getMaxValue(ClientSession mongoSession, String collection, String fieldName) {
242
        Document doc = collection(collection).find(mongoSession).projection(new Document(fieldName, 1)).sort(new Document(fieldName, -1)).first();
63✔
243
        if (doc == null) {
6✔
244
            return null;
6✔
245
        }
246
        return doc.get(fieldName);
12✔
247
    }
248

249
    /**
250
     * Retrieves the document with the maximum value of a specified field from the documents matching the given filter in the specified collection.
251
     *
252
     * @param mongoSession the MongoDB client session
253
     * @param collection   the name of the collection
254
     * @param find         the filter to match documents
255
     * @param fieldName    the field for which to find the maximum value
256
     * @return the document with the maximum value of the specified field, or null if no matching documents exist
257
     */
258
    public static Document getMaxValueDocument(ClientSession mongoSession, String collection, Bson find, String fieldName) {
259
        return collection(collection).find(mongoSession, find).sort(new Document(fieldName, -1)).first();
45✔
260
    }
261

262
    /**
263
     * Sets or updates a document in the specified collection.
264
     *
265
     * @param mongoSession the MongoDB client session
266
     * @param collection   the name of the collection
267
     * @param update       the document to set or update (must contain an _id field)
268
     */
269
    public static void set(ClientSession mongoSession, String collection, Document update) {
270
        Bson find = new Document("_id", update.get("_id"));
24✔
271
        MongoCursor<Document> cursor = collection(collection).find(mongoSession, find).cursor();
21✔
272
        if (cursor.hasNext()) {
9✔
273
            collection(collection).updateOne(mongoSession, find, new Document("$set", update));
33✔
274
        }
275
    }
3✔
276

277
    /**
278
     * Inserts a document into the specified collection.
279
     *
280
     * @param mongoSession the MongoDB client session
281
     * @param collection   the name of the collection
282
     * @param doc          the document to insert
283
     */
284
    public static void insert(ClientSession mongoSession, String collection, Document doc) {
285
        collection(collection).insertOne(mongoSession, doc);
15✔
286
    }
3✔
287

288
    /**
289
     * Sets the value of an element with the given name in the specified collection.
290
     * If the element does not exist, it will be created.
291
     *
292
     * @param mongoSession the MongoDB client session
293
     * @param collection   the name of the collection
294
     * @param elementId    the name of the element used as the _id field
295
     * @param value        the value to set
296
     */
297
    public static void setValue(ClientSession mongoSession, String collection, String elementId, Object value) {
298
        collection(collection).updateOne(mongoSession, new Document("_id", elementId), new Document("$set", new Document("value", value)), new UpdateOptions().upsert(true));
72✔
299
    }
3✔
300

301
    /**
302
     * Records the hash of a given value in the "hashes" collection.
303
     * If the hash already exists, it will be ignored.
304
     *
305
     * @param mongoSession the MongoDB client session
306
     * @param value        the value to hash and record
307
     */
308
    public static void recordHash(ClientSession mongoSession, String value) {
309
        try {
310
            insert(mongoSession, "hashes", new Document("value", value).append("hash", Utils.getHash(value)));
36✔
311
        } catch (MongoWriteException e) {
×
312
            // Duplicate key error -- ignore it
313
            if (e.getError().getCode() != 11000) throw e;
×
314
        }
3✔
315
    }
3✔
316

317
    /**
318
     * Retrieves the original value corresponding to a given hash from the "hashes" collection.
319
     *
320
     * @param hash the hash to look up
321
     * @return the original value, or null if not found
322
     */
323
    public static String unhash(String hash) {
324
        try (var c = collection("hashes").find(new Document("hash", hash)).cursor()) {
30✔
325
            if (c.hasNext()) {
9✔
326
                return c.next().getString("value");
24✔
327
            }
328
            return null;
12✔
329
        }
12!
330
    }
331

332
    /**
333
     * Loads a nanopublication into the database.
334
     *
335
     * @param mongoSession the MongoDB client session
336
     * @param nanopub      the nanopublication to load
337
     */
338
    public static boolean loadNanopub(ClientSession mongoSession, Nanopub nanopub) {
339
        return loadNanopub(mongoSession, nanopub, null);
21✔
340
    }
341

342
    /**
343
     * Loads a nanopublication into the database, optionally filtering by public key hash and types.
344
     *
345
     * @param mongoSession the MongoDB client session
346
     * @param nanopub      the nanopublication to load
347
     * @param pubkeyHash   the public key hash to filter by (can be null)
348
     * @param types        the types to filter by (can be empty)
349
     * @return true if the nanopublication was loaded, false otherwise
350
     */
351
    public static boolean loadNanopub(ClientSession mongoSession, Nanopub nanopub, String pubkeyHash, String... types) {
352
        if (nanopub.getTripleCount() > 1200) {
12!
353
            logger.info("Nanopub has too many triples ({}): {}", nanopub.getTripleCount(), nanopub.getUri());
×
354
            return false;
×
355
        }
356
        if (nanopub.getByteCount() > 1000000) {
15!
357
            logger.info("Nanopub is too large ({}): {}", nanopub.getByteCount(), nanopub.getUri());
×
358
            return false;
×
359
        }
360
        String pubkey = getPubkey(nanopub);
9✔
361
        if (pubkey == null) {
6!
362
            logger.info("Ignoring invalid nanopub: {}", nanopub.getUri());
×
363
            return false;
×
364
        }
365
        String ph = Utils.getHash(pubkey);
9✔
366
        if (pubkeyHash != null && !pubkeyHash.equals(ph)) {
6!
367
            logger.info("Ignoring nanopub with non-matching pubkey: {}", nanopub.getUri());
×
368
            return false;
×
369
        }
370
        recordHash(mongoSession, pubkey);
9✔
371

372
        String ac = TrustyUriUtils.getArtifactCode(nanopub.getUri().stringValue());
15✔
373
        if (ac == null) {
6!
374
            // I don't think this ever happens, but checking here to be sure
375
            logger.info("ERROR. Unexpected Trusty URI: {}", nanopub.getUri());
×
376
            return false;
×
377
        }
378
        if (has(mongoSession, Collection.NANOPUBS.toString(), ac)) {
18!
379
            logger.info("Already loaded: {}", nanopub.getUri());
×
380
        } else {
381
            Long counter = (Long) getMaxValue(mongoSession, Collection.NANOPUBS.toString(), "counter");
21✔
382
            if (counter == null) counter = 0l;
15!
383
            String nanopubString;
384
            byte[] jellyContent;
385
            try {
386
                nanopubString = NanopubUtils.writeToString(nanopub, RDFFormat.TRIG);
12✔
387
                // Save the same thing in the Jelly format for faster loading
388
                jellyContent = JellyUtils.writeNanopubForDB(nanopub);
9✔
389
            } catch (IOException ex) {
×
390
                throw new RuntimeException(ex);
×
391
            }
3✔
392
            collection(Collection.NANOPUBS.toString()).insertOne(mongoSession, new Document("_id", ac).append("fullId", nanopub.getUri().stringValue()).append("counter", counter + 1).append("pubkey", ph).append("content", nanopubString).append("jelly", new Binary(jellyContent)));
102✔
393

394
            for (IRI invalidatedId : Utils.getInvalidatedNanopubIds(nanopub)) {
33✔
395
                String invalidatedAc = TrustyUriUtils.getArtifactCode(invalidatedId.stringValue());
12✔
396
                if (invalidatedAc == null) continue;  // This should never happen; checking here just to be sure
6!
397

398
                // Add this nanopub also to all lists of invalidated nanopubs:
399
                collection("invalidations").insertOne(mongoSession, new Document("invalidatingNp", ac).append("invalidatingPubkey", ph).append("invalidatedNp", invalidatedAc));
45✔
400
                MongoCursor<Document> invalidatedEntries = collection("listEntries").find(mongoSession, new Document("np", invalidatedAc).append("pubkey", ph)).cursor();
42✔
401
                while (invalidatedEntries.hasNext()) {
9!
402
                    Document invalidatedEntry = invalidatedEntries.next();
×
403
                    addToList(mongoSession, nanopub, ph, invalidatedEntry.getString("type"));
×
404
                }
×
405

406
                collection("listEntries").updateMany(mongoSession, new Document("np", invalidatedAc).append("pubkey", ph), new Document("$set", new Document("invalidated", true)));
69✔
407
                collection("trustEdges").updateMany(mongoSession, new Document("source", invalidatedAc), new Document("$set", new Document("invalidated", true)));
60✔
408
            }
3✔
409
        }
410

411
        if (pubkeyHash != null) {
6!
412
            for (String type : types) {
×
413
                // TODO Check if nanopub really has the type?
414
                addToList(mongoSession, nanopub, pubkeyHash, Utils.getTypeHash(mongoSession, type));
×
415
                if (type.equals("$")) {
×
416
                    for (IRI t : NanopubUtils.getTypes(nanopub)) {
×
417
                        addToList(mongoSession, nanopub, pubkeyHash, Utils.getTypeHash(mongoSession, t));
×
418
                    }
×
419
                }
420
            }
421
        }
422

423
        // Add the invalidating nanopubs also to the lists of this nanopub:
424
        try (MongoCursor<Document> invalidations = collection("invalidations").find(mongoSession, new Document("invalidatedNp", ac).append("invalidatingPubkey", ph)).cursor()) {
42✔
425
            if (invalidations.hasNext()) {
9!
426
                collection("listEntries").updateMany(mongoSession, new Document("np", ac).append("pubkey", ph), new Document("$set", new Document("invalidated", true)));
×
427
                collection("trustEdges").updateMany(mongoSession, new Document("source", ac), new Document("$set", new Document("invalidated", true)));
×
428
            }
429
            while (invalidations.hasNext()) {
9!
430
                String iac = invalidations.next().getString("invalidatingNp");
×
431
                try {
432
                    Document npDoc = collection(Collection.NANOPUBS.toString()).find(mongoSession, new Document("_id", iac)).projection(new Document("jelly", 1)).first();
×
433
                    Nanopub inp = JellyUtils.readFromDB(npDoc.get("jelly", Binary.class).getData());
×
434
                    for (IRI type : NanopubUtils.getTypes(inp)) {
×
435
                        addToList(mongoSession, inp, ph, Utils.getTypeHash(mongoSession, type));
×
436
                    }
×
437
                } catch (RDF4JException | MalformedNanopubException ex) {
×
438
                    ex.printStackTrace();
×
439
                }
×
440
            }
×
441

442
        }
443

444
        return true;
6✔
445
    }
446

447
    private static void addToList(ClientSession mongoSession, Nanopub nanopub, String pubkeyHash, String typeHash) {
448
        String ac = TrustyUriUtils.getArtifactCode(nanopub.getUri().stringValue());
×
449
        try {
450
            insert(mongoSession, "lists", new Document("pubkey", pubkeyHash).append("type", typeHash));
×
451
        } catch (MongoWriteException e) {
×
452
            // Duplicate key error -- ignore it
453
            if (e.getError().getCode() != 11000) throw e;
×
454
        }
×
455

456
        if (has(mongoSession, "listEntries", new Document("pubkey", pubkeyHash).append("type", typeHash).append("np", ac))) {
×
457
            logger.info("Already listed: {}", nanopub.getUri());
×
458
        } else {
459

460
            Document doc = getMaxValueDocument(mongoSession, "listEntries", new Document("pubkey", pubkeyHash).append("type", typeHash), "position");
×
461
            long position;
462
            String checksum;
463
            if (doc == null) {
×
464
                position = 0l;
×
465
                checksum = NanopubUtils.updateXorChecksum(nanopub.getUri(), NanopubUtils.INIT_CHECKSUM);
×
466
            } else {
467
                position = doc.getLong("position") + 1;
×
468
                checksum = NanopubUtils.updateXorChecksum(nanopub.getUri(), doc.getString("checksum"));
×
469
            }
470
            collection("listEntries").insertOne(mongoSession, new Document("pubkey", pubkeyHash).append("type", typeHash).append("position", position).append("np", ac).append("checksum", checksum).append("invalidated", false));
×
471
        }
472
    }
×
473

474
    /**
475
     * Returns the public key string of the Nanopub's signature, or null if not available or invalid.
476
     *
477
     * @param nanopub the nanopub to extract the public key from
478
     * @return The public key string, or null if not available or invalid.
479
     */
480
    public static String getPubkey(Nanopub nanopub) {
481
        // TODO shouldn't this be moved to a utility class in nanopub-java? there is a similar method in NanopubElement class of nanodash
482
        NanopubSignatureElement el;
483
        try {
484
            el = SignatureUtils.getSignatureElement(nanopub);
9✔
485
            if (el != null && SignatureUtils.hasValidSignature(el) && el.getPublicKeyString() != null) {
24!
486
                return el.getPublicKeyString();
9✔
487
            }
488
        } catch (MalformedCryptoElementException | GeneralSecurityException ex) {
×
489
            logger.error("Error in checking the signature of the nanopub {}", nanopub.getUri());
×
490
        }
3✔
491
        return null;
6✔
492
    }
493

494
    /**
495
     * Calculates a hash representing the current state of the trust paths in the loading collection.
496
     *
497
     * @param mongoSession the MongoDB client session
498
     * @return the calculated trust state hash
499
     */
500
    public static String calculateTrustStateHash(ClientSession mongoSession) {
501
        MongoCursor<Document> tp = collection("trustPaths_loading").find(mongoSession).sort(ascending("_id")).cursor();
×
502
        // TODO Improve this so we don't create the full string just for calculating its hash:
503
        String s = "";
×
504
        while (tp.hasNext()) {
×
505
            Document d = tp.next();
×
506
            s += d.getString("_id") + " (" + d.getString("type") + ")\n";
×
507
        }
×
508
        return Utils.getHash(s);
×
509
    }
510

511
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc