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

knowledgepixels / nanopub-registry / 24727603152

21 Apr 2026 02:18PM UTC coverage: 31.808% (+0.3%) from 31.558%
24727603152

push

github

ashleycaselli
chore(logging): enhance info error handling in Nanopub processing

280 of 986 branches covered (28.4%)

Branch coverage included in aggregate %.

839 of 2532 relevant lines covered (33.14%)

5.5 hits per line

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

33.15
src/main/java/com/knowledgepixels/registry/RegistryPeerConnector.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 org.apache.http.HttpResponse;
8
import org.apache.http.client.methods.HttpGet;
9
import org.apache.http.client.methods.HttpHead;
10
import org.apache.http.util.EntityUtils;
11
import org.bson.Document;
12
import org.nanopub.NanopubUtils;
13
import org.nanopub.jelly.NanopubStream;
14
import org.slf4j.Logger;
15
import org.slf4j.LoggerFactory;
16

17
import java.io.IOException;
18
import java.io.InputStream;
19
import java.util.ArrayList;
20
import java.util.Collections;
21
import java.util.List;
22
import java.util.concurrent.atomic.AtomicLong;
23

24
import static com.knowledgepixels.registry.RegistryDB.*;
25

26
/**
27
 * Checks peer Nanopub Registries for new nanopublications and loads them.
28
 */
29
public class RegistryPeerConnector {
30

31
    private RegistryPeerConnector() {}
32

33
    private static final Logger log = LoggerFactory.getLogger(RegistryPeerConnector.class);
12✔
34

35
    public static void checkPeers(ClientSession s) {
36
        List<String> peerUrls = new ArrayList<>(Utils.getPeerUrls());
×
37
        Collections.shuffle(peerUrls);
×
38

39
        for (String peerUrl : peerUrls) {
×
40
            try {
41
                checkPeer(s, peerUrl);
×
42
            } catch (Exception ex) {
×
43
                log.warn("Failed to check peer {}: {}", peerUrl, ex.getMessage(), ex);
×
44
            }
×
45
        }
×
46
    }
×
47

48
    static void checkPeer(ClientSession s, String peerUrl) throws IOException {
49
        log.info("Checking peer: {}", peerUrl);
×
50

51
        HttpResponse resp = NanopubUtils.getHttpClient().execute(new HttpHead(peerUrl));
×
52
        int httpStatus = resp.getStatusLine().getStatusCode();
×
53
        EntityUtils.consumeQuietly(resp.getEntity());
×
54
        if (httpStatus < 200 || httpStatus >= 300) {
×
55
            log.warn("Failed to reach peer {} (HTTP {}); skipping", peerUrl, httpStatus);
×
56
            return;
×
57
        }
58

59
        if (isTestInstance(resp)) {
×
60
            log.info("Skipping peer {} because it is a test instance", peerUrl);
×
61
            return;
×
62
        }
63

64
        String status = getHeader(resp, "Nanopub-Registry-Status");
×
65
        if (!"ready".equals(status) && !"updating".equals(status)) {
×
66
            log.warn("Skipping peer {}: registry status is '{}' (expected 'ready' or 'updating')", peerUrl, status);
×
67
            return;
×
68
        }
69

70
        Long peerSetupId = getHeaderLong(resp, "Nanopub-Registry-Setup-Id");
×
71
        Long peerLoadCounter = getHeaderLong(resp, "Nanopub-Registry-Load-Counter");
×
72
        if (peerSetupId == null || peerLoadCounter == null) {
×
73
            log.warn("Skipping peer {}: missing required headers Nanopub-Registry-Setup-Id or Nanopub-Registry-Load-Counter", peerUrl);
×
74
            return;
×
75
        }
76

77
        syncWithPeer(s, peerUrl, peerSetupId, peerLoadCounter);
×
78
    }
×
79

80
    static void syncWithPeer(ClientSession s, String peerUrl, long peerSetupId, long peerLoadCounter) {
81
        Document peerState = getPeerState(s, peerUrl);
12✔
82
        Long lastSetupId = peerState != null ? peerState.getLong("setupId") : null;
24✔
83
        Long lastLoadCounter = peerState != null ? peerState.getLong("loadCounter") : null;
24✔
84

85
        if (lastSetupId != null && !lastSetupId.equals(peerSetupId)) {
21✔
86
            log.info("Peer {} was reset (setupId changed), resetting tracking", peerUrl);
12✔
87
            deletePeerState(s, peerUrl);
9✔
88
            lastLoadCounter = null;
6✔
89
        }
90

91
        long effectiveCounter = lastLoadCounter != null ? lastLoadCounter : 0;
21✔
92

93
        if (lastLoadCounter != null && lastLoadCounter.equals(peerLoadCounter)) {
21!
94
            log.info("Peer {} has no new nanopubs (loadCounter unchanged: {})", peerUrl, peerLoadCounter);
21✔
95
        } else if (lastLoadCounter != null) {
6!
96
            // Fetch all nanopubs added since our last known position.
97
            log.info("Peer {} has new nanopubs (loadCounter {} -> {}), fetching recent", peerUrl, lastLoadCounter, peerLoadCounter);
×
98
            long lastReceived = loadRecentNanopubs(s, peerUrl, lastLoadCounter);
×
99
            if (lastReceived > 0) {
×
100
                effectiveCounter = lastReceived;
×
101
            }
102
            // Only discover new pubkeys when the peer has new data
103
            discoverPubkeys(s, peerUrl);
×
104
        } else {
×
105
            log.info("Peer {} is new, pubkey discovery will handle initial sync", peerUrl);
12✔
106
            discoverPubkeys(s, peerUrl);
9✔
107
        }
108
        updatePeerState(s, peerUrl, peerSetupId, effectiveCounter);
15✔
109
    }
3✔
110

111
    /**
112
     * Fetches nanopubs from a peer after the given counter.
113
     *
114
     * @return the counter of the last successfully received nanopub, or -1 if none were received
115
     */
116
    private static long loadRecentNanopubs(ClientSession s, String peerUrl, long afterCounter) {
117
        String requestUrl = peerUrl + "nanopubs.jelly?afterCounter=" + afterCounter;
×
118
        log.info("Fetching recent nanopubs from: {}", requestUrl);
×
119
        AtomicLong lastReceivedCounter = new AtomicLong(-1);
×
120
        try {
121
            HttpResponse resp = NanopubUtils.getHttpClient().execute(new HttpGet(requestUrl));
×
122
            int httpStatus = resp.getStatusLine().getStatusCode();
×
123
            if (httpStatus < 200 || httpStatus >= 300) {
×
124
                EntityUtils.consumeQuietly(resp.getEntity());
×
125
                log.warn("Fetching recent nanopubs from {} failed (HTTP {}); skipping", requestUrl, httpStatus);
×
126
                return -1;
×
127
            }
128
            try (InputStream is = resp.getEntity().getContent()) {
×
129
                NanopubLoader.loadStreamInParallel(
×
130
                        NanopubStream.fromByteStream(is).getAsNanopubs().peek(m -> {
×
131
                            // Track counter in the main thread as items are consumed from the stream
132
                            if (m.isSuccess() && m.getCounter() > 0) {
×
133
                                lastReceivedCounter.set(m.getCounter());
×
134
                            }
135
                        }),
×
136
                        np -> {
137
                            if (!CoverageFilter.isCovered(np)) {
×
138
                                return;
×
139
                            }
140
                            try (ClientSession workerSession = RegistryDB.getClient().startSession()) {
×
141
                                String pubkey = RegistryDB.getPubkey(np);
×
142
                                if (pubkey != null) {
×
143
                                    NanopubLoader.simpleLoad(workerSession, np, pubkey);
×
144
                                }
145
                            }
146
                        });
×
147
            }
148
        } catch (IOException ex) {
×
149
            log.warn("Failed to fetch recent nanopubs from {}: {}", peerUrl, ex.getMessage(), ex);
×
150
        }
×
151
        log.info("Last received counter from {}: {}", peerUrl, lastReceivedCounter.get());
×
152
        return lastReceivedCounter.get();
×
153
    }
154

155
    static void discoverPubkeys(ClientSession s, String peerUrl) {
156
        log.info("Discovering pubkeys from peer: {}", peerUrl);
12✔
157
        try {
158
            List<String> peerPubkeys = Utils.retrieveListFromJsonUrl(peerUrl + "pubkeys.json");
×
159
            int discovered = 0;
×
160
            for (String pubkeyHash : peerPubkeys) {
×
161
                Document filter = new Document("pubkey", pubkeyHash).append("type", NanopubLoader.INTRO_TYPE_HASH);
×
162
                if (!has(s, "lists", filter)) {
×
163
                    try {
164
                        insert(s, "lists", new Document("pubkey", pubkeyHash)
×
165
                                .append("type", NanopubLoader.INTRO_TYPE_HASH)
×
166
                                .append("status", EntryStatus.encountered.getValue()));
×
167
                    } catch (MongoWriteException e) {
×
168
                        if (e.getError().getCategory() != ErrorCategory.DUPLICATE_KEY) {
×
169
                            throw e;
×
170
                        }
171
                    }
×
172
                    discovered++;
×
173
                } else if (!has(s, "lists", new Document(filter).append("status", EntryStatus.loaded.getValue()))) {
×
174
                    // Set status to encountered if not already loaded (fixes null-status entries from older code)
175
                    collection("lists").updateMany(s, filter,
×
176
                            new Document("$set", new Document("status", EntryStatus.encountered.getValue())));
×
177
                    discovered++;
×
178
                }
179
            }
×
180
            log.info("Discovered {} new pubkeys from peer {}", discovered, peerUrl);
×
181
        } catch (Exception ex) {
3✔
182
            log.warn("Failed to discover pubkeys from {}: {}", peerUrl, ex.getMessage(), ex);
54✔
183
        }
×
184
    }
3✔
185

186
    static Document getPeerState(ClientSession s, String peerUrl) {
187
        try (MongoCursor<Document> cursor = collection(Collection.PEER_STATE.toString())
27✔
188
                .find(s, new Document("_id", peerUrl)).cursor()) {
9✔
189
            return cursor.hasNext() ? cursor.next() : null;
33✔
190
        }
191
    }
192

193
    static void updatePeerState(ClientSession s, String peerUrl, long setupId, long loadCounter) {
194
        collection(Collection.PEER_STATE.toString()).updateOne(s,
63✔
195
                new Document("_id", peerUrl),
196
                new Document("$set", new Document("_id", peerUrl)
197
                        .append("setupId", setupId)
12✔
198
                        .append("loadCounter", loadCounter)
9✔
199
                        .append("lastChecked", System.currentTimeMillis())),
24✔
200
                new com.mongodb.client.model.UpdateOptions().upsert(true));
3✔
201
    }
3✔
202

203
    static void deletePeerState(ClientSession s, String peerUrl) {
204
        collection(Collection.PEER_STATE.toString()).deleteOne(s, new Document("_id", peerUrl));
33✔
205
    }
3✔
206

207
    static boolean isTestInstance(HttpResponse resp) {
208
        return "true".equals(getHeader(resp, "Nanopub-Registry-Test-Instance"));
18✔
209
    }
210

211
    static String getHeader(HttpResponse resp, String name) {
212
        return resp.getFirstHeader(name) != null ? resp.getFirstHeader(name).getValue() : null;
33✔
213
    }
214

215
    static Long getHeaderLong(HttpResponse resp, String name) {
216
        String value = getHeader(resp, name);
12✔
217
        if (value == null || "null".equals(value)) {
18✔
218
            return null;
6✔
219
        }
220
        try {
221
            return Long.parseLong(value);
12✔
222
        } catch (NumberFormatException ex) {
3✔
223
            return null;
6✔
224
        }
225
    }
226

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