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

knowledgepixels / nanopub-registry / 23018791468

12 Mar 2026 06:56PM UTC coverage: 25.927% (-0.8%) from 26.77%
23018791468

push

github

web-flow
Merge pull request #81 from knowledgepixels/feature/load-all-pubkeys

Add REGISTRY_PRIORITIZE_ALL_PUBKEYS and remove full fetch

156 of 670 branches covered (23.28%)

Branch coverage included in aggregate %.

529 of 1972 relevant lines covered (26.83%)

4.79 hits per line

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

34.57
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

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.info("Error checking peer {}: {}", peerUrl, ex.getMessage());
×
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.info("Failed to reach peer {}: {}", peerUrl, httpStatus);
×
56
            return;
×
57
        }
58

59
        String status = getHeader(resp, "Nanopub-Registry-Status");
×
60
        if (!"ready".equals(status) && !"updating".equals(status)) {
×
61
            log.info("Peer {} in non-ready state: {}", peerUrl, status);
×
62
            return;
×
63
        }
64

65
        Long peerSetupId = getHeaderLong(resp, "Nanopub-Registry-Setup-Id");
×
66
        Long peerLoadCounter = getHeaderLong(resp, "Nanopub-Registry-Load-Counter");
×
67
        if (peerSetupId == null || peerLoadCounter == null) {
×
68
            log.info("Peer {} missing setupId or loadCounter headers", peerUrl);
×
69
            return;
×
70
        }
71

72
        syncWithPeer(s, peerUrl, peerSetupId, peerLoadCounter);
×
73
    }
×
74

75
    static void syncWithPeer(ClientSession s, String peerUrl, long peerSetupId, long peerLoadCounter) {
76
        Document peerState = getPeerState(s, peerUrl);
12✔
77
        Long lastSetupId = peerState != null ? peerState.getLong("setupId") : null;
24✔
78
        Long lastLoadCounter = peerState != null ? peerState.getLong("loadCounter") : null;
24✔
79

80
        if (lastSetupId != null && !lastSetupId.equals(peerSetupId)) {
21✔
81
            log.info("Peer {} was reset (setupId changed), resetting tracking", peerUrl);
12✔
82
            deletePeerState(s, peerUrl);
9✔
83
            lastLoadCounter = null;
6✔
84
        }
85

86
        if (lastLoadCounter != null && lastLoadCounter.equals(peerLoadCounter)) {
21!
87
            log.info("Peer {} has no new nanopubs (loadCounter unchanged: {})", peerUrl, peerLoadCounter);
21✔
88
        } else if (lastLoadCounter != null) {
6!
89
            // Fetch all nanopubs added since our last known position.
90
            // TODO Add per-pubkey afterCounter tracking for more targeted incremental sync
91
            long delta = peerLoadCounter - lastLoadCounter;
×
92
            log.info("Peer {} has {} new nanopubs, fetching recent", peerUrl, delta);
×
93
            loadRecentNanopubs(s, peerUrl, lastLoadCounter);
×
94
        } else {
×
95
            log.info("Peer {} is new, pubkey discovery will handle initial sync", peerUrl);
12✔
96
        }
97

98
        discoverPubkeys(s, peerUrl);
9✔
99
        updatePeerState(s, peerUrl, peerSetupId, peerLoadCounter);
15✔
100
    }
3✔
101

102
    private static void loadRecentNanopubs(ClientSession s, String peerUrl, long afterCounter) {
103
        String requestUrl = peerUrl + "nanopubs.jelly?afterCounter=" + afterCounter;
×
104
        log.info("Fetching recent nanopubs from: {}", requestUrl);
×
105
        try {
106
            HttpResponse resp = NanopubUtils.getHttpClient().execute(new HttpGet(requestUrl));
×
107
            int httpStatus = resp.getStatusLine().getStatusCode();
×
108
            if (httpStatus < 200 || httpStatus >= 300) {
×
109
                EntityUtils.consumeQuietly(resp.getEntity());
×
110
                log.info("Request failed: {} {}", requestUrl, httpStatus);
×
111
                return;
×
112
            }
113
            try (InputStream is = resp.getEntity().getContent()) {
×
114
                NanopubStream.fromByteStream(is).getAsNanopubs().forEach(m -> {
×
115
                    if (m.isSuccess()) {
×
116
                        Nanopub np = null;
×
117
                        try {
118
                            np = m.getNanopub();
×
119
                            RegistryDB.loadNanopub(s, np);
×
120
                            NanopubLoader.simpleLoad(s, np);
×
121
                        } catch (Exception ex) {
×
122
                            log.warn("Skipping nanopub {} during recent fetch: {}",
×
123
                                    np != null ? np.getUri() : "unknown", ex.getMessage());
×
124
                        }
×
125
                    }
126
                });
×
127
            }
128
        } catch (IOException ex) {
×
129
            log.info("Failed to fetch recent nanopubs from {}: {}", peerUrl, ex.getMessage());
×
130
        }
×
131
    }
×
132

133
    static void discoverPubkeys(ClientSession s, String peerUrl) {
134
        log.info("Discovering pubkeys from peer: {}", peerUrl);
12✔
135
        try {
136
            List<String> peerPubkeys = Utils.retrieveListFromJsonUrl(peerUrl + "pubkeys.json");
×
137
            int discovered = 0;
×
138
            for (String pubkeyHash : peerPubkeys) {
×
139
                Document filter = new Document("pubkey", pubkeyHash).append("type", NanopubLoader.INTRO_TYPE_HASH);
×
140
                if (!has(s, "lists", filter)) {
×
141
                    try {
142
                        insert(s, "lists", new Document("pubkey", pubkeyHash)
×
143
                                .append("type", NanopubLoader.INTRO_TYPE_HASH)
×
144
                                .append("status", EntryStatus.encountered.getValue()));
×
145
                    } catch (MongoWriteException e) {
×
146
                        if (e.getError().getCategory() != ErrorCategory.DUPLICATE_KEY) throw e;
×
147
                    }
×
148
                    discovered++;
×
149
                } else if (!has(s, "lists", new Document(filter).append("status", EntryStatus.loaded.getValue()))) {
×
150
                    // Set status to encountered if not already loaded (fixes null-status entries from older code)
151
                    collection("lists").updateMany(s, filter,
×
152
                            new Document("$set", new Document("status", EntryStatus.encountered.getValue())));
×
153
                    discovered++;
×
154
                }
155
            }
×
156
            log.info("Discovered {} new pubkeys from peer {}", discovered, peerUrl);
×
157
        } catch (Exception ex) {
3✔
158
            log.info("Failed to discover pubkeys from {}: {}", peerUrl, ex.getMessage());
18✔
159
        }
×
160
    }
3✔
161

162
    static Document getPeerState(ClientSession s, String peerUrl) {
163
        try (MongoCursor<Document> cursor = collection(Collection.PEER_STATE.toString())
27✔
164
                .find(s, new Document("_id", peerUrl)).cursor()) {
9✔
165
            return cursor.hasNext() ? cursor.next() : null;
33✔
166
        }
167
    }
168

169
    static void updatePeerState(ClientSession s, String peerUrl, long setupId, long loadCounter) {
170
        collection(Collection.PEER_STATE.toString()).updateOne(s,
63✔
171
                new Document("_id", peerUrl),
172
                new Document("$set", new Document("_id", peerUrl)
173
                        .append("setupId", setupId)
12✔
174
                        .append("loadCounter", loadCounter)
9✔
175
                        .append("lastChecked", System.currentTimeMillis())),
24✔
176
                new com.mongodb.client.model.UpdateOptions().upsert(true));
3✔
177
    }
3✔
178

179
    static void deletePeerState(ClientSession s, String peerUrl) {
180
        collection(Collection.PEER_STATE.toString()).deleteOne(s, new Document("_id", peerUrl));
33✔
181
    }
3✔
182

183
    static String getHeader(HttpResponse resp, String name) {
184
        return resp.getFirstHeader(name) != null ? resp.getFirstHeader(name).getValue() : null;
33✔
185
    }
186

187
    static Long getHeaderLong(HttpResponse resp, String name) {
188
        String value = getHeader(resp, name);
12✔
189
        if (value == null || "null".equals(value)) return null;
24✔
190
        try {
191
            return Long.parseLong(value);
12✔
192
        } catch (NumberFormatException ex) {
3✔
193
            return null;
6✔
194
        }
195
    }
196

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