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

knowledgepixels / nanopub-registry / 23539426481

25 Mar 2026 11:47AM UTC coverage: 30.645% (+0.2%) from 30.443%
23539426481

push

github

web-flow
Merge pull request #88 from knowledgepixels/perf/eliminate-redundant-signature-verification

perf: eliminate redundant signature verification in POST and peer sync

190 of 700 branches covered (27.14%)

Branch coverage included in aggregate %.

646 of 2028 relevant lines covered (31.85%)

5.39 hits per line

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

32.43
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.Nanopub;
13
import org.nanopub.NanopubUtils;
14
import org.nanopub.jelly.NanopubStream;
15
import org.slf4j.Logger;
16
import org.slf4j.LoggerFactory;
17

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

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

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

32
    private RegistryPeerConnector() {}
33

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

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

40
        for (String peerUrl : peerUrls) {
×
41
            try {
42
                checkPeer(s, peerUrl);
×
43
            } catch (Exception ex) {
×
44
                log.info("Error checking peer {}: {}", peerUrl, ex.getMessage());
×
45
            }
×
46
        }
×
47
    }
×
48

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

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

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

65
        String status = getHeader(resp, "Nanopub-Registry-Status");
×
66
        if (!"ready".equals(status) && !"updating".equals(status)) {
×
67
            log.info("Peer {} in non-ready state: {}", peerUrl, status);
×
68
            return;
×
69
        }
70

71
        Long peerSetupId = getHeaderLong(resp, "Nanopub-Registry-Setup-Id");
×
72
        Long peerLoadCounter = getHeaderLong(resp, "Nanopub-Registry-Load-Counter");
×
73
        if (peerSetupId == null || peerLoadCounter == null) {
×
74
            log.info("Peer {} missing setupId or loadCounter headers", peerUrl);
×
75
            return;
×
76
        }
77

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

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

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

92
        long effectiveLoadCounter = lastLoadCounter != null ? lastLoadCounter : 0;
21✔
93

94
        if (lastLoadCounter != null && lastLoadCounter.equals(peerLoadCounter)) {
21!
95
            log.info("Peer {} has no new nanopubs (loadCounter unchanged: {})", peerUrl, peerLoadCounter);
21✔
96
        } else if (lastLoadCounter != null) {
6!
97
            // Fetch all nanopubs added since our last known position.
98
            // TODO Add per-pubkey afterCounter tracking for more targeted incremental sync
99
            long delta = peerLoadCounter - lastLoadCounter;
×
100
            log.info("Peer {} has {} new nanopubs, fetching recent", peerUrl, delta);
×
101
            long lastReceived = loadRecentNanopubs(s, peerUrl, lastLoadCounter);
×
102
            if (lastReceived > 0) {
×
103
                effectiveLoadCounter = lastReceived;
×
104
            }
105
        } else {
×
106
            log.info("Peer {} is new, pubkey discovery will handle initial sync", peerUrl);
12✔
107
        }
108

109
        discoverPubkeys(s, peerUrl);
9✔
110
        updatePeerState(s, peerUrl, peerSetupId, effectiveLoadCounter);
15✔
111
    }
3✔
112

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

157
    static void discoverPubkeys(ClientSession s, String peerUrl) {
158
        log.info("Discovering pubkeys from peer: {}", peerUrl);
12✔
159
        try {
160
            List<String> peerPubkeys = Utils.retrieveListFromJsonUrl(peerUrl + "pubkeys.json");
×
161
            int discovered = 0;
×
162
            for (String pubkeyHash : peerPubkeys) {
×
163
                Document filter = new Document("pubkey", pubkeyHash).append("type", NanopubLoader.INTRO_TYPE_HASH);
×
164
                if (!has(s, "lists", filter)) {
×
165
                    try {
166
                        insert(s, "lists", new Document("pubkey", pubkeyHash)
×
167
                                .append("type", NanopubLoader.INTRO_TYPE_HASH)
×
168
                                .append("status", EntryStatus.encountered.getValue()));
×
169
                    } catch (MongoWriteException e) {
×
170
                        if (e.getError().getCategory() != ErrorCategory.DUPLICATE_KEY) throw e;
×
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.info("Failed to discover pubkeys from {}: {}", peerUrl, ex.getMessage());
18✔
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)) return null;
24✔
218
        try {
219
            return Long.parseLong(value);
12✔
220
        } catch (NumberFormatException ex) {
3✔
221
            return null;
6✔
222
        }
223
    }
224

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