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

knowledgepixels / nanopub-registry / 28113618611

24 Jun 2026 04:28PM UTC coverage: 31.926% (-0.2%) from 32.089%
28113618611

Pull #116

github

web-flow
Merge d931f8afc into eebd16ba4
Pull Request #116: Enhance and standardize logging across multiple components

313 of 1106 branches covered (28.3%)

Branch coverage included in aggregate %.

1048 of 3157 relevant lines covered (33.2%)

5.51 hits per line

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

8.03
src/main/java/com/knowledgepixels/registry/NanopubLoader.java
1
package com.knowledgepixels.registry;
2

3
import com.mongodb.ErrorCategory;
4
import com.mongodb.MongoWriteException;
5
import com.mongodb.client.ClientSession;
6
import com.mongodb.client.MongoCursor;
7
import net.trustyuri.TrustyUriUtils;
8
import net.trustyuri.rdf.RdfModule;
9
import org.apache.http.Header;
10
import org.apache.http.HttpResponse;
11
import org.apache.http.client.HttpClient;
12
import org.apache.http.client.methods.CloseableHttpResponse;
13
import org.apache.http.client.methods.HttpGet;
14
import org.apache.http.util.EntityUtils;
15
import org.bson.Document;
16
import org.bson.types.Binary;
17
import org.eclipse.rdf4j.common.exception.RDF4JException;
18
import org.eclipse.rdf4j.rio.RDFFormat;
19
import org.nanopub.MalformedNanopubException;
20
import org.nanopub.Nanopub;
21
import org.nanopub.NanopubImpl;
22
import org.nanopub.NanopubUtils;
23
import org.nanopub.extra.server.GetNanopub;
24
import org.nanopub.jelly.JellyUtils;
25
import org.nanopub.jelly.MaybeNanopub;
26
import org.nanopub.jelly.NanopubStream;
27
import org.nanopub.trusty.TrustyNanopubUtils;
28
import org.nanopub.vocabulary.NPX;
29
import org.slf4j.Logger;
30
import org.slf4j.LoggerFactory;
31

32
import java.io.IOException;
33
import java.io.InputStream;
34
import java.util.ArrayList;
35
import java.util.Collections;
36
import java.util.List;
37
import java.util.concurrent.ExecutorService;
38
import java.util.concurrent.Executors;
39
import java.util.concurrent.Semaphore;
40
import java.util.concurrent.TimeUnit;
41
import java.util.concurrent.atomic.AtomicReference;
42
import java.util.function.Consumer;
43
import java.util.stream.Stream;
44

45
import static com.knowledgepixels.registry.RegistryDB.has;
46
import static com.knowledgepixels.registry.RegistryDB.insert;
47

48
public class NanopubLoader {
49

50
    private NanopubLoader() {
51
    }
52

53
    public final static String INTRO_TYPE = NPX.DECLARED_BY.stringValue();
9✔
54
    public final static String INTRO_TYPE_HASH = Utils.getHash(INTRO_TYPE);
9✔
55
    public final static String ENDORSE_TYPE = Utils.APPROVES_OF.stringValue();
9✔
56
    public final static String ENDORSE_TYPE_HASH = Utils.getHash(ENDORSE_TYPE);
9✔
57
    private static final Logger logger = LoggerFactory.getLogger(NanopubLoader.class);
9✔
58

59
    // TODO Distinguish and support these cases:
60
    //      1. Simple load: load to all core lists if pubkey is "core-loaded", or load to all lists if pubkey is "full-loaded"
61
    //      2. Core load: load to all core lists (initialize if needed), or load to all lists if pubkey is "full-loaded"
62
    //      3. Full load: load to all lists (initialize if needed)
63

64
    public static void simpleLoad(ClientSession mongoSession, String nanopubId) {
65
        simpleLoad(mongoSession, nanopubId, true);
×
66
    }
×
67

68
    public static void simpleLoad(ClientSession mongoSession, String nanopubId, boolean persistOnRetrieve) {
69
        if (persistOnRetrieve) {
×
70
            simpleLoad(mongoSession, retrieveNanopub(mongoSession, nanopubId));
×
71
        } else {
72
            Nanopub np = retrieveLocalNanopub(mongoSession, nanopubId);
×
73
            if (np == null) {
×
74
                logger.debug("Nanopub {} not found locally; fetching from peers without persisting on retrieve", nanopubId);
×
75
                np = getNanopub(nanopubId);
×
76
            }
77
            if (np != null) {
×
78
                simpleLoad(mongoSession, np);
×
79
            } else {
80
                logger.warn("Could not retrieve nanopub {} from any peer; skipping load", nanopubId);
×
81
            }
82
        }
83
    }
×
84

85
    public static void simpleLoad(ClientSession mongoSession, Nanopub np) {
86
        String pubkey = RegistryDB.getPubkey(np);
×
87
        if (pubkey == null) {
×
88
            logger.warn("Skipping load of nanopub {}: no valid signature found, so its public key could not be determined", np.getUri());
×
89
            return;
×
90
        }
91
        simpleLoad(mongoSession, np, pubkey);
×
92
    }
×
93

94
    /**
95
     * Loads a nanopub to the appropriate lists, using a pre-verified public key
96
     * to skip redundant signature verification.
97
     */
98
    public static void simpleLoad(ClientSession mongoSession, Nanopub np, String verifiedPubkey) {
99
        String pubkeyHash = Utils.getHash(verifiedPubkey);
9✔
100
        // TODO Do we need to load anything else here, into the other DB collections?
101
        if (has(mongoSession, "lists", new Document("pubkey", pubkeyHash).append("type", "$").append("status", "loaded"))) {
45!
102
            logger.debug("Loading nanopub {} into full-loaded lists for pubkey {}", np.getUri(), pubkeyHash);
×
103
            RegistryDB.loadNanopubVerified(mongoSession, np, verifiedPubkey, pubkeyHash, "$");
×
104
        } else if (has(mongoSession, "lists", new Document("pubkey", pubkeyHash).append("type", INTRO_TYPE_HASH).append("status", "loaded"))) {
45!
105
            logger.debug("Loading nanopub {} into core lists (intro/endorse) for pubkey {}", np.getUri(), pubkeyHash);
×
106
            RegistryDB.loadNanopubVerified(mongoSession, np, verifiedPubkey, pubkeyHash, INTRO_TYPE, ENDORSE_TYPE);
×
107
        } else {
108
            // Pubkey not yet loaded (unknown or in transitional "encountered" state): store the
109
            // nanopub in the nanopubs collection so it is not lost. RUN_OPTIONAL_LOAD will add it
110
            // to the appropriate lists once the pubkey's intro/endorse have been fetched.
111
            logger.debug("Pubkey {} not yet loaded; storing nanopub {} without adding it to any list yet", pubkeyHash, np.getUri());
18✔
112
            RegistryDB.loadNanopubVerified(mongoSession, np, verifiedPubkey, null);
24✔
113
            if (!has(mongoSession, "lists", new Document("pubkey", pubkeyHash).append("type", INTRO_TYPE_HASH))) {
36!
114
                // Unknown pubkey: create encountered intro list so RUN_OPTIONAL_LOAD picks it up
115
                try {
116
                    logger.info("Encountered new pubkey {}; creating intro list entry so it can be processed by RUN_OPTIONAL_LOAD", pubkeyHash);
12✔
117
                    insert(mongoSession, "lists", new Document("pubkey", pubkeyHash)
30✔
118
                            .append("type", INTRO_TYPE_HASH)
9✔
119
                            .append("status", EntryStatus.encountered.getValue()));
6✔
120
                } catch (MongoWriteException e) {
×
121
                    if (e.getError().getCategory() != ErrorCategory.DUPLICATE_KEY) {
×
122
                        throw e;
×
123
                    }
124
                    logger.debug("Intro list entry for pubkey {} was already created concurrently; ignoring duplicate-key error", pubkeyHash);
×
125
                }
3✔
126
            }
127
        }
128
    }
3✔
129

130
    private static final int LOAD_PARALLELISM = Integer.parseInt(
12✔
131
            Utils.getEnv("REGISTRY_LOAD_PARALLELISM", String.valueOf(Runtime.getRuntime().availableProcessors())));
12✔
132

133
    /**
134
     * Processes a stream of nanopubs in parallel using a thread pool.
135
     * Each worker thread uses its own MongoDB ClientSession.
136
     * Backpressure is applied via a semaphore to avoid unbounded memory growth.
137
     *
138
     * @param stream    the nanopub stream to process
139
     * @param processor consumer that processes each nanopub (called with its own ClientSession)
140
     */
141
    public static void loadStreamInParallel(Stream<MaybeNanopub> stream, Consumer<Nanopub> processor) {
142
        if (LOAD_PARALLELISM <= 1) {
×
143
            // Fall back to sequential processing
144
            logger.debug("REGISTRY_LOAD_PARALLELISM={}; processing nanopub stream sequentially", LOAD_PARALLELISM);
×
145
            stream.forEach(m -> {
×
146
                if (!m.isSuccess()) {
×
147
                    logger.error("Failed to download a nanopub from the stream; aborting task");
×
148
                    throw new AbortingTaskException("Failed to download nanopub; aborting task...");
×
149
                }
150
                processor.accept(m.getNanopub());
×
151
            });
×
152
            return;
×
153
        }
154

155
        logger.debug("Processing nanopub stream in parallel with {} worker threads", LOAD_PARALLELISM);
×
156
        ExecutorService executor = Executors.newFixedThreadPool(LOAD_PARALLELISM);
×
157
        Semaphore semaphore = new Semaphore(LOAD_PARALLELISM * 2);
×
158
        AtomicReference<Exception> error = new AtomicReference<>();
×
159

160
        try {
161
            stream.forEach(m -> {
×
162
                if (error.get() != null) {
×
163
                    return;
×
164
                }
165
                if (!m.isSuccess()) {
×
166
                    logger.error("Failed to download a nanopub from the stream; aborting remaining work");
×
167
                    error.compareAndSet(null, new AbortingTaskException("Failed to download nanopub; aborting task..."));
×
168
                    return;
×
169
                }
170
                Nanopub np = m.getNanopub();
×
171
                try {
172
                    semaphore.acquire();
×
173
                } catch (InterruptedException e) {
×
174
                    Thread.currentThread().interrupt();
×
175
                    logger.warn("Interrupted while waiting for a free worker slot; aborting parallel load", e);
×
176
                    error.compareAndSet(null, e);
×
177
                    return;
×
178
                }
×
179
                executor.submit(() -> {
×
180
                    try {
181
                        processor.accept(np);
×
182
                    } catch (Exception e) {
×
183
                        logger.error("Worker thread failed while processing nanopub {}: {}", np.getUri(), e.getMessage(), e);
×
184
                        error.compareAndSet(null, e);
×
185
                    } finally {
186
                        semaphore.release();
×
187
                    }
188
                });
×
189
            });
×
190
        } finally {
191
            executor.shutdown();
×
192
            try {
193
                if (!executor.awaitTermination(1, TimeUnit.HOURS)) {
×
194
                    logger.warn("Worker pool did not terminate within the 1-hour timeout after shutdown");
×
195
                }
196
            } catch (InterruptedException e) {
×
197
                Thread.currentThread().interrupt();
×
198
                logger.warn("Interrupted while waiting for worker pool to terminate", e);
×
199
            }
×
200
        }
201

202
        if (error.get() != null) {
×
203
            logger.error("Parallel nanopub loading failed: {}", error.get().getMessage());
×
204
            if (error.get() instanceof RuntimeException re) {
×
205
                throw re;
×
206
            }
207
            throw new RuntimeException("Parallel loading failed", error.get());
×
208
        }
209
    }
×
210

211
    /**
212
     * Retrieve Nanopubs from the peers of this Nanopub Registry.
213
     *
214
     * @param typeHash   The hash of the type of the Nanopub to retrieve.
215
     * @param pubkeyHash The hash of the pubkey of the Nanopub to retrieve.
216
     * @return A stream of MaybeNanopub objects, or an empty stream if no peer is available.
217
     */
218
    public static Stream<MaybeNanopub> retrieveNanopubsFromPeers(String typeHash, String pubkeyHash) {
219
        return retrieveNanopubsFromPeers(typeHash, pubkeyHash, null);
×
220
    }
221

222
    /**
223
     * Retrieve Nanopubs from the peers, optionally skipping ahead using checksums.
224
     *
225
     * @param typeHash       The hash of the type of the Nanopub to retrieve.
226
     * @param pubkeyHash     The hash of the pubkey of the Nanopub to retrieve.
227
     * @param afterChecksums Comma-separated checksums for skip-ahead (geometric fallback), or null for full fetch.
228
     * @return A stream of MaybeNanopub objects, or an empty stream if no peer is available.
229
     */
230
    public static Stream<MaybeNanopub> retrieveNanopubsFromPeers(String typeHash, String pubkeyHash, String afterChecksums) {
231
        // TODO Move the code of this method to nanopub-java library.
232

233
        List<String> peerUrlsToTry = new ArrayList<>(Utils.getPeerUrls());
×
234
        Collections.shuffle(peerUrlsToTry);
×
235
        if (peerUrlsToTry.isEmpty()) {
×
236
            logger.warn("No peers configured; cannot retrieve nanopub list for pubkey {} / type {}", pubkeyHash, typeHash);
×
237
        }
238
        while (!peerUrlsToTry.isEmpty()) {
×
239
            String peerUrl = peerUrlsToTry.removeFirst();
×
240

241
            String requestUrl = peerUrl + "list/" + pubkeyHash + "/" + typeHash + ".jelly";
×
242
            if (afterChecksums != null) {
×
243
                requestUrl += "?afterChecksums=" + afterChecksums;
×
244
            }
245
            logger.debug("Fetching nanopub list from peer: {}", requestUrl);
×
246
            try {
247
                CloseableHttpResponse resp = NanopubUtils.getHttpClient().execute(new HttpGet(requestUrl));
×
248
                int httpStatus = resp.getStatusLine().getStatusCode();
×
249
                if (httpStatus < 200 || httpStatus >= 300) {
×
250
                    logger.warn("Peer {} returned HTTP {} for nanopub list request {}; trying next peer", peerUrl, httpStatus, requestUrl);
×
251
                    EntityUtils.consumeQuietly(resp.getEntity());
×
252
                    continue;
×
253
                }
254
                Header nrStatus = resp.getFirstHeader("Nanopub-Registry-Status");
×
255
                if (nrStatus == null) {
×
256
                    logger.warn("Peer {} did not return a Nanopub-Registry-Status header for {}; trying next peer", peerUrl, requestUrl);
×
257
                    EntityUtils.consumeQuietly(resp.getEntity());
×
258
                    continue;
×
259
                } else if (!nrStatus.getValue().equals("ready") && !nrStatus.getValue().equals("updating")) {
×
260
                    logger.warn("Skipping peer {}: registry status is '{}' (expected 'ready' or 'updating'); trying next peer", peerUrl, nrStatus.getValue());
×
261
                    EntityUtils.consumeQuietly(resp.getEntity());
×
262
                    continue;
×
263
                }
264
                logger.debug("Successfully fetched nanopub list from peer {} (status: {})", peerUrl, nrStatus.getValue());
×
265
                InputStream is = resp.getEntity().getContent();
×
266
                return NanopubStream.fromByteStream(is).getAsNanopubs().onClose(() -> {
×
267
                    try {
268
                        resp.close();
×
269
                    } catch (IOException e) {
×
270
                        logger.debug("Error closing HTTP response from peer {}", peerUrl, e);
×
271
                    }
×
272
                });
×
273
            } catch (UnsupportedOperationException | IOException ex) {
×
274
                logger.warn("Failed to fetch nanopub list from peer {} ({}): {}", peerUrl, requestUrl, ex.getMessage(), ex);
×
275
            }
276
        }
×
277
        logger.warn("Exhausted all peers without successfully retrieving nanopub list for pubkey {} / type {}", pubkeyHash, typeHash);
×
278
        return Stream.empty();
×
279
    }
280

281
    public static Nanopub retrieveNanopub(ClientSession mongoSession, String nanopubId) {
282
        Nanopub np = retrieveLocalNanopub(mongoSession, nanopubId);
×
283
        int tryCount = 0;
×
284
        while (np == null) {
×
285
            if (tryCount > 10) {
×
286
                logger.error("Giving up on retrieving nanopub {} after {} attempts", nanopubId, tryCount);
×
287
                throw new RuntimeException("Could not load nanopub: " + nanopubId);
×
288
            } else if (tryCount > 0) {
×
289
                try {
290
                    Thread.sleep(100);
×
291
                } catch (InterruptedException ex) {
×
292
                    logger.warn("Thread interrupted while waiting to retry nanopub retrieval for {}", nanopubId, ex);
×
293
                }
×
294
            }
295
            logger.info("Nanopub {} not found locally; fetching from peers (attempt {} of 10)", nanopubId, tryCount + 1);
×
296

297
            // TODO Reach out to other Nanopub Registries here:
298
            np = getNanopub(nanopubId);
×
299
            if (np != null) {
×
300
                logger.debug("Retrieved nanopub {} from a peer; persisting it locally", nanopubId);
×
301
                RegistryDB.loadNanopub(mongoSession, np);
×
302
            } else {
303
                logger.debug("Attempt {} to retrieve nanopub {} from peers failed", tryCount + 1, nanopubId);
×
304
                tryCount = tryCount + 1;
×
305
            }
306
        }
307
        return np;
×
308
    }
309

310
    public static Nanopub retrieveLocalNanopub(ClientSession mongoSession, String nanopubId) {
311
        String ac = TrustyUriUtils.getArtifactCode(nanopubId);
×
312
        MongoCursor<Document> cursor = RegistryDB.get(mongoSession, Collection.NANOPUBS.toString(), new Document("_id", ac));
×
313
        if (!cursor.hasNext()) {
×
314
            return null;
×
315
        }
316
        try {
317
            // Parse from Jelly, not TriG (it's faster)
318
            return JellyUtils.readFromDB(((Binary) cursor.next().get("jelly")).getData());
×
319
        } catch (RDF4JException | MalformedNanopubException ex) {
×
320
            logger.error("Failed to parse locally stored Jelly content for nanopub '{}'; treating it as missing", nanopubId, ex);
×
321
            return null;
×
322
        }
323
    }
324

325
    // TODO Provide this method in nanopub-java (GetNanopub)
326
    private static Nanopub getNanopub(String uriOrArtifactCode) {
327
        List<String> peerUrls = new ArrayList<>(Utils.getPeerUrls());
×
328
        Collections.shuffle(peerUrls);
×
329
        String ac = GetNanopub.getArtifactCode(uriOrArtifactCode).toString();
×
330
        if (!ac.startsWith(RdfModule.MODULE_ID)) {
×
331
            throw new IllegalArgumentException("Not a trusty URI of type RA");
×
332
        }
333
        if (peerUrls.isEmpty()) {
×
334
            logger.warn("No peers configured; cannot fetch nanopub {}", ac);
×
335
        }
336
        while (!peerUrls.isEmpty()) {
×
337
            String peerUrl = peerUrls.removeFirst();
×
338
            try {
339
                Nanopub np = get(ac, peerUrl, NanopubUtils.getHttpClient());
×
340
                if (np != null) {
×
341
                    logger.debug("Successfully fetched nanopub {} from peer {}", ac, peerUrl);
×
342
                    return np;
×
343
                }
344
            } catch (IOException | RDF4JException | MalformedNanopubException ex) {
×
345
                logger.debug("Failed to fetch nanopub {} from peer {}: {}", ac, peerUrl, ex.getMessage(), ex);
×
346
            }
×
347
        }
×
348
        logger.warn("Could not fetch nanopub {} from any of the {} configured peer(s)", ac, Utils.getPeerUrls().size());
×
349
        return null;
×
350
    }
351

352
    // TODO Provide this method in nanopub-java (GetNanopub)
353
    private static Nanopub get(String artifactCode, String registryUrl, HttpClient httpClient)
354
            throws IOException, RDF4JException, MalformedNanopubException {
355
        HttpGet get = null;
×
356
        // TODO Get in Jelly format:
357
        String getUrl = registryUrl + "np/" + artifactCode;
×
358
        try {
359
            get = new HttpGet(getUrl);
×
360
        } catch (IllegalArgumentException ex) {
×
361
            throw new IOException("invalid URL: " + getUrl);
×
362
        }
×
363
        get.setHeader("Accept", "application/trig");
×
364
        InputStream in = null;
×
365
        try {
366
            HttpResponse resp = httpClient.execute(get);
×
367
            if (!wasSuccessful(resp)) {
×
368
                EntityUtils.consumeQuietly(resp.getEntity());
×
369
                throw new IOException("Request to " + getUrl + " failed: " + resp.getStatusLine());
×
370
            }
371
            in = resp.getEntity().getContent();
×
372
            Nanopub nanopub = new NanopubImpl(in, RDFFormat.TRIG);
×
373
            if (!TrustyNanopubUtils.isValidTrustyNanopub(nanopub)) {
×
374
                throw new MalformedNanopubException("Nanopub retrieved from " + registryUrl + " is not a valid trusty nanopub");
×
375
            }
376
            return nanopub;
×
377
        } finally {
378
            if (in != null) {
×
379
                in.close();
×
380
            }
381
        }
382
    }
383

384
    private static boolean wasSuccessful(HttpResponse resp) {
385
        int c = resp.getStatusLine().getStatusCode();
×
386
        return c >= 200 && c < 300;
×
387
    }
388

389
}
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