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

knowledgepixels / nanopub-registry / 23249943389

18 Mar 2026 02:32PM UTC coverage: 30.235% (-0.02%) from 30.259%
23249943389

push

github

web-flow
Merge pull request #86 from knowledgepixels/fix/peer-sync-transaction-timeout

Fix peer sync stalling due to MongoDB transaction timeout

187 of 686 branches covered (27.26%)

Branch coverage included in aggregate %.

623 of 1993 relevant lines covered (31.26%)

5.28 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
            // 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
                            RegistryDB.loadNanopub(s, np);
×
136
                            NanopubLoader.simpleLoad(s, np);
×
137
                            if (m.getCounter() > 0) {
×
138
                                lastReceivedCounter.set(m.getCounter());
×
139
                            }
140
                        } catch (Exception ex) {
×
141
                            log.warn("Skipping nanopub {} during recent fetch: {}",
×
142
                                    np != null ? np.getUri() : "unknown", ex.getMessage());
×
143
                        }
×
144
                    }
145
                });
×
146
            }
147
        } catch (IOException ex) {
×
148
            log.info("Failed to fetch recent nanopubs from {}: {}", peerUrl, ex.getMessage());
×
149
        }
×
150
        log.info("Last received counter from {}: {}", peerUrl, lastReceivedCounter.get());
×
151
        return lastReceivedCounter.get();
×
152
    }
153

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

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

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

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

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

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

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

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