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

knowledgepixels / nanopub-registry / 24138607049

08 Apr 2026 01:42PM UTC coverage: 32.47% (-0.4%) from 32.824%
24138607049

Pull #99

github

web-flow
Merge 336546501 into 689a63b39
Pull Request #99: Fix peer sync race with committed counter watermark

268 of 926 branches covered (28.94%)

Branch coverage included in aggregate %.

797 of 2354 relevant lines covered (33.86%)

5.7 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.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
            log.info("Peer {} has new nanopubs (loadCounter {} -> {}), fetching recent", peerUrl, lastLoadCounter, peerLoadCounter);
×
99
            long lastReceived = loadRecentNanopubs(s, peerUrl, lastLoadCounter);
×
100
            if (lastReceived > 0) {
×
101
                effectiveLoadCounter = lastReceived;
×
102
            }
103
            // Only discover new pubkeys when the peer has new data
104
            discoverPubkeys(s, peerUrl);
×
105
        } else {
×
106
            log.info("Peer {} is new, pubkey discovery will handle initial sync", peerUrl);
12✔
107
            discoverPubkeys(s, peerUrl);
9✔
108
        }
109
        updatePeerState(s, peerUrl, peerSetupId, effectiveLoadCounter);
15✔
110
    }
3✔
111

112
    /**
113
     * Fetches nanopubs from a peer after the given counter.
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.info("Request failed: {} {}", 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)) return;
×
138
                            try (ClientSession workerSession = RegistryDB.getClient().startSession()) {
×
139
                                String pubkey = RegistryDB.getPubkey(np);
×
140
                                if (pubkey != null) {
×
141
                                    NanopubLoader.simpleLoad(workerSession, np, pubkey);
×
142
                                }
143
                            }
144
                        });
×
145
            }
146
        } catch (IOException ex) {
×
147
            log.info("Failed to fetch recent nanopubs from {}: {}", peerUrl, ex.getMessage());
×
148
        }
×
149
        log.info("Last received counter from {}: {}", peerUrl, lastReceivedCounter.get());
×
150
        return lastReceivedCounter.get();
×
151
    }
152

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

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

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

199
    static void deletePeerState(ClientSession s, String peerUrl) {
200
        collection(Collection.PEER_STATE.toString()).deleteOne(s, new Document("_id", peerUrl));
33✔
201
    }
3✔
202

203
    static boolean isTestInstance(HttpResponse resp) {
204
        return "true".equals(getHeader(resp, "Nanopub-Registry-Test-Instance"));
18✔
205
    }
206

207
    static String getHeader(HttpResponse resp, String name) {
208
        return resp.getFirstHeader(name) != null ? resp.getFirstHeader(name).getValue() : null;
33✔
209
    }
210

211
    static Long getHeaderLong(HttpResponse resp, String name) {
212
        String value = getHeader(resp, name);
12✔
213
        if (value == null || "null".equals(value)) return null;
24✔
214
        try {
215
            return Long.parseLong(value);
12✔
216
        } catch (NumberFormatException ex) {
3✔
217
            return null;
6✔
218
        }
219
    }
220

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