• 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

12.91
src/main/java/com/knowledgepixels/registry/Task.java
1
package com.knowledgepixels.registry;
2

3
import com.knowledgepixels.registry.db.IndexInitializer;
4
import com.mongodb.client.ClientSession;
5
import com.mongodb.client.FindIterable;
6
import com.mongodb.client.MongoCollection;
7
import com.mongodb.client.MongoCursor;
8
import net.trustyuri.TrustyUriUtils;
9
import org.apache.commons.lang.Validate;
10
import org.bson.Document;
11
import org.eclipse.rdf4j.model.IRI;
12
import org.eclipse.rdf4j.model.Statement;
13
import org.nanopub.Nanopub;
14
import org.nanopub.extra.index.IndexUtils;
15
import org.nanopub.extra.index.NanopubIndex;
16
import org.nanopub.extra.security.KeyDeclaration;
17
import org.nanopub.extra.setting.IntroNanopub;
18
import org.nanopub.extra.setting.NanopubSetting;
19
import org.slf4j.Logger;
20
import org.slf4j.LoggerFactory;
21

22
import java.io.Serializable;
23
import java.time.ZonedDateTime;
24
import java.util.*;
25
import java.util.concurrent.atomic.AtomicLong;
26

27
import static com.knowledgepixels.registry.EntryStatus.*;
28
import static com.knowledgepixels.registry.NanopubLoader.*;
29
import static com.knowledgepixels.registry.RegistryDB.*;
30
import static com.knowledgepixels.registry.ServerStatus.*;
31
import static com.mongodb.client.model.Filters.eq;
32
import static com.mongodb.client.model.Sorts.*;
33

34
public enum Task implements Serializable {
6✔
35

36
    INIT_DB {
33✔
37
        public void run(ClientSession s, Document taskDoc) {
38
            setServerStatus(s, launching);
9✔
39

40
            increaseStateCounter(s);
6✔
41
            if (RegistryDB.isInitialized(s)) {
9!
42
                throw new RuntimeException("DB already initialized");
×
43
            }
44
            setValue(s, Collection.SERVER_INFO.toString(), "setupId", Math.abs(Utils.getRandom().nextLong()));
27✔
45
            setValue(s, Collection.SERVER_INFO.toString(), "testInstance", "true".equals(System.getenv("REGISTRY_TEST_INSTANCE")));
30✔
46
            schedule(s, LOAD_CONFIG);
9✔
47
        }
3✔
48

49
    },
50

51
    LOAD_CONFIG {
33✔
52
        public void run(ClientSession s, Document taskDoc) {
53
            if (getServerStatus(s) != launching) {
12!
54
                throw new IllegalTaskStatusException("Illegal status for this task: " + getServerStatus(s));
×
55
            }
56

57
            if (System.getenv("REGISTRY_COVERAGE_TYPES") != null) {
9!
58
                setValue(s, Collection.SERVER_INFO.toString(), "coverageTypes", System.getenv("REGISTRY_COVERAGE_TYPES"));
×
59
            }
60
            if (System.getenv("REGISTRY_COVERAGE_AGENTS") != null) {
9!
61
                setValue(s, Collection.SERVER_INFO.toString(), "coverageAgents", System.getenv("REGISTRY_COVERAGE_AGENTS"));
×
62
            }
63
            schedule(s, LOAD_SETTING);
9✔
64
        }
3✔
65

66
    },
67

68
    LOAD_SETTING {
33✔
69
        public void run(ClientSession s, Document taskDoc) throws Exception {
70
            if (getServerStatus(s) != launching) {
12!
71
                throw new IllegalTaskStatusException("Illegal status for this task: " + getServerStatus(s));
×
72
            }
73

74
            NanopubSetting settingNp = Utils.getSetting();
6✔
75
            String settingId = TrustyUriUtils.getArtifactCode(settingNp.getNanopub().getUri().stringValue());
18✔
76
            setValue(s, Collection.SETTING.toString(), "original", settingId);
18✔
77
            setValue(s, Collection.SETTING.toString(), "current", settingId);
18✔
78
            loadNanopub(s, settingNp.getNanopub());
15✔
79
            List<Document> bootstrapServices = new ArrayList<>();
12✔
80
            for (IRI i : settingNp.getBootstrapServices()) {
33✔
81
                bootstrapServices.add(new Document("_id", i.stringValue()));
27✔
82
            }
3✔
83
            // potentially currently hardcoded in the nanopub lib
84
            setValue(s, Collection.SETTING.toString(), "bootstrap-services", bootstrapServices);
18✔
85

86
            if (!"false".equals(System.getenv("REGISTRY_PERFORM_FULL_LOAD"))) {
15!
87
                schedule(s, LOAD_FULL.withDelay(60 * 1000));
15✔
88
            }
89

90
            setServerStatus(s, coreLoading);
9✔
91
            schedule(s, INIT_COLLECTIONS);
9✔
92
        }
3✔
93

94
    },
95

96
    INIT_COLLECTIONS {
33✔
97

98
        // DB read from:
99
        // DB write to:  trustPaths, endorsements, accounts
100
        // This state is periodically executed
101

102
        public void run(ClientSession s, Document taskDoc) throws Exception {
103
            if (getServerStatus(s) != coreLoading && getServerStatus(s) != updating) {
×
104
                throw new IllegalTaskStatusException("Illegal status for this task: " + getServerStatus(s));
×
105
            }
106

107
            IndexInitializer.initLoadingCollections(s);
×
108

109
            // since this may take long, we start with postfix "_loading"
110
            // and only at completion it's changed to trustPath, endorsements, accounts
111
            insert(s, "trustPaths_loading",
×
112
                    new Document("_id", "$")
113
                            .append("sorthash", "")
×
114
                            .append("agent", "$")
×
115
                            .append("pubkey", "$")
×
116
                            .append("depth", 0)
×
117
                            .append("ratio", 1.0d)
×
118
                            .append("type", "extended")
×
119
            );
120

121
            NanopubIndex agentIndex = IndexUtils.castToIndex(NanopubLoader.retrieveNanopub(s, Utils.getSetting().getAgentIntroCollection().stringValue()));
×
122
            loadNanopub(s, agentIndex);
×
123
            for (IRI el : agentIndex.getElements()) {
×
124
                String declarationAc = TrustyUriUtils.getArtifactCode(el.stringValue());
×
125
                Validate.notNull(declarationAc);
×
126

127
                insert(s, "endorsements_loading",
×
128
                        new Document("agent", "$")
129
                                .append("pubkey", "$")
×
130
                                .append("endorsedNanopub", declarationAc)
×
131
                                .append("source", getValue(s, Collection.SETTING.toString(), "current").toString())
×
132
                                .append("status", toRetrieve.getValue())
×
133

134
                );
135

136
            }
×
137
            insert(s, "accounts_loading",
×
138
                    new Document("agent", "$")
139
                            .append("pubkey", "$")
×
140
                            .append("status", visited.getValue())
×
141
                            .append("depth", 0)
×
142
            );
143

144
            log.info("Starting iteration at depth 0");
×
145
            schedule(s, LOAD_DECLARATIONS.with("depth", 1));
×
146
        }
×
147

148
        // At the end of this task, the base agent is initialized:
149
        // ------------------------------------------------------------
150
        //
151
        //              $$$$ ----endorses----> [intro]
152
        //              base                (to-retrieve)
153
        //              $$$$
154
        //            (visited)
155
        //
156
        //              [0] trust path
157
        //
158
        // ------------------------------------------------------------
159
        // Only one endorses-link to an introduction is shown here,
160
        // but there are typically several.
161

162
    },
163

164
    LOAD_DECLARATIONS {
33✔
165

166
        // In general, we have at this point accounts with
167
        // endorsement links to unvisited agent introductions:
168
        // ------------------------------------------------------------
169
        //
170
        //         o      ----endorses----> [intro]
171
        //    --> /#\  /o\___            (to-retrieve)
172
        //        / \  \_/^^^
173
        //         (visited)
174
        //
175
        //    ========[X] trust path
176
        //
177
        // ------------------------------------------------------------
178

179
        // DB read from: endorsements, trustEdges, accounts
180
        // DB write to:  endorsements, trustEdges, accounts
181

182
        public void run(ClientSession s, Document taskDoc) {
183

184
            int depth = taskDoc.getInteger("depth");
×
185

186
            if (has(s, "endorsements_loading", new Document("status", toRetrieve.getValue()))) {
×
187
                Document d = getOne(s, "endorsements_loading",
×
188
                        new DbEntryWrapper(toRetrieve).getDocument());
×
189

190
                IntroNanopub agentIntro = getAgentIntro(s, d.getString("endorsedNanopub"));
×
191
                if (agentIntro != null) {
×
192
                    String agentId = agentIntro.getUser().stringValue();
×
193

194
                    for (KeyDeclaration kd : agentIntro.getKeyDeclarations()) {
×
195
                        String sourceAgent = d.getString("agent");
×
196
                        Validate.notNull(sourceAgent);
×
197
                        String sourcePubkey = d.getString("pubkey");
×
198
                        Validate.notNull(sourcePubkey);
×
199
                        String sourceAc = d.getString("source");
×
200
                        Validate.notNull(sourceAc);
×
201
                        String agentPubkey = Utils.getHash(kd.getPublicKeyString());
×
202
                        Validate.notNull(agentPubkey);
×
203
                        Document trustEdge = new Document("fromAgent", sourceAgent)
×
204
                                .append("fromPubkey", sourcePubkey)
×
205
                                .append("toAgent", agentId)
×
206
                                .append("toPubkey", agentPubkey)
×
207
                                .append("source", sourceAc);
×
208
                        if (!has(s, "trustEdges", trustEdge)) {
×
209
                            boolean invalidated = has(s, "invalidations", new Document("invalidatedNp", sourceAc).append("invalidatingPubkey", sourcePubkey));
×
210
                            insert(s, "trustEdges", trustEdge.append("invalidated", invalidated));
×
211
                        }
212

213
                        Document agent = new Document("agent", agentId).append("pubkey", agentPubkey);
×
214
                        if (!has(s, "accounts_loading", agent)) {
×
215
                            insert(s, "accounts_loading", agent.append("status", seen.getValue()).append("depth", depth));
×
216
                        }
217
                    }
×
218

219
                    set(s, "endorsements_loading", d.append("status", retrieved.getValue()));
×
220
                } else {
×
221
                    set(s, "endorsements_loading", d.append("status", discarded.getValue()));
×
222
                }
223

224
                schedule(s, LOAD_DECLARATIONS.with("depth", depth));
×
225

226
            } else {
×
227
                schedule(s, EXPAND_TRUST_PATHS.with("depth", depth));
×
228
            }
229
        }
×
230

231
        // At the end of this step, the key declarations in the agent
232
        // introductions are loaded and the corresponding trust edges
233
        // established:
234
        // ------------------------------------------------------------
235
        //
236
        //        o      ----endorses----> [intro]
237
        //   --> /#\  /o\___                o
238
        //       / \  \_/^^^ ---trusts---> /#\  /o\___
239
        //        (visited)                / \  \_/^^^
240
        //                                   (seen)
241
        //
242
        //   ========[X] trust path
243
        //
244
        // ------------------------------------------------------------
245
        // Only one trust edge per introduction is shown here, but
246
        // there can be several.
247

248
    },
249

250
    EXPAND_TRUST_PATHS {
33✔
251

252
        // DB read from: accounts, trustPaths, trustEdges
253
        // DB write to:  accounts, trustPaths
254

255
        public void run(ClientSession s, Document taskDoc) {
256

257
            int depth = taskDoc.getInteger("depth");
×
258

259
            Document d = getOne(s, "accounts_loading",
×
260
                    new Document("status", visited.getValue())
×
261
                            .append("depth", depth - 1)
×
262
            );
263

264
            if (d != null) {
×
265

266
                String agentId = d.getString("agent");
×
267
                Validate.notNull(agentId);
×
268
                String pubkeyHash = d.getString("pubkey");
×
269
                Validate.notNull(pubkeyHash);
×
270

271
                Document trustPath = collection("trustPaths_loading").find(s,
×
272
                        new Document("agent", agentId).append("pubkey", pubkeyHash).append("type", "extended").append("depth", depth - 1)
×
273
                ).sort(orderBy(descending("ratio"), ascending("sorthash"))).first();
×
274

275
                if (trustPath == null) {
×
276
                    // Check it again in next iteration:
277
                    set(s, "accounts_loading", d.append("depth", depth));
×
278
                } else {
279
                    // Only first matching trust path is considered
280

281
                    Map<String, Document> newPaths = new HashMap<>();
×
282
                    Map<String, Set<String>> pubkeySets = new HashMap<>();
×
283
                    String currentSetting = getValue(s, Collection.SETTING.toString(), "current").toString();
×
284

285
                    MongoCursor<Document> edgeCursor = get(s, "trustEdges",
×
286
                            new Document("fromAgent", agentId)
287
                                    .append("fromPubkey", pubkeyHash)
×
288
                                    .append("invalidated", false)
×
289
                    );
290
                    while (edgeCursor.hasNext()) {
×
291
                        Document e = edgeCursor.next();
×
292

293
                        String agent = e.getString("toAgent");
×
294
                        Validate.notNull(agent);
×
295
                        String pubkey = e.getString("toPubkey");
×
296
                        Validate.notNull(pubkey);
×
297
                        String pathId = trustPath.getString("_id") + " " + agent + "|" + pubkey;
×
298
                        newPaths.put(pathId,
×
299
                                new Document("_id", pathId)
300
                                        .append("sorthash", Utils.getHash(currentSetting + " " + pathId))
×
301
                                        .append("agent", agent)
×
302
                                        .append("pubkey", pubkey)
×
303
                                        .append("depth", depth)
×
304
                                        .append("type", "extended")
×
305
                        );
306
                        if (!pubkeySets.containsKey(agent)) pubkeySets.put(agent, new HashSet<>());
×
307
                        pubkeySets.get(agent).add(pubkey);
×
308
                    }
×
309
                    for (String pathId : newPaths.keySet()) {
×
310
                        Document pd = newPaths.get(pathId);
×
311
                        // first divide by agents; then for each agent, divide by number of pubkeys:
312
                        double newRatio = (trustPath.getDouble("ratio") * 0.9) / pubkeySets.size() / pubkeySets.get(pd.getString("agent")).size();
×
313
                        insert(s, "trustPaths_loading", pd.append("ratio", newRatio));
×
314
                    }
×
315
                    set(s, "trustPaths_loading", trustPath.append("type", "primary"));
×
316
                    set(s, "accounts_loading", d.append("status", expanded.getValue()));
×
317
                }
318
                schedule(s, EXPAND_TRUST_PATHS.with("depth", depth));
×
319

320
            } else {
×
321

322
                schedule(s, LOAD_CORE.with("depth", depth).append("load-count", 0));
×
323

324
            }
325

326
        }
×
327

328
        // At the end of this step, trust paths are updated to include
329
        // the new accounts:
330
        // ------------------------------------------------------------
331
        //
332
        //         o      ----endorses----> [intro]
333
        //    --> /#\  /o\___                o
334
        //        / \  \_/^^^ ---trusts---> /#\  /o\___
335
        //        (expanded)                / \  \_/^^^
336
        //                                    (seen)
337
        //
338
        //    ========[X]=====================[X+1] trust path
339
        //
340
        // ------------------------------------------------------------
341
        // Only one trust path is shown here, but they branch out if
342
        // several trust edges are present.
343

344
    },
345

346
    LOAD_CORE {
33✔
347

348
        // From here on, we refocus on the head of the trust paths:
349
        // ------------------------------------------------------------
350
        //
351
        //         o
352
        //    --> /#\  /o\___
353
        //        / \  \_/^^^
354
        //          (seen)
355
        //
356
        //    ========[X] trust path
357
        //
358
        // ------------------------------------------------------------
359

360
        // DB read from: accounts, trustPaths, endorsements, lists
361
        // DB write to:  accounts, endorsements, lists
362

363
        public void run(ClientSession s, Document taskDoc) {
364

365
            int depth = taskDoc.getInteger("depth");
×
366
            int loadCount = taskDoc.getInteger("load-count");
×
367

368
            Document agentAccount = getOne(s, "accounts_loading",
×
369
                    new Document("depth", depth).append("status", seen.getValue()));
×
370
            final String agentId;
371
            final String pubkeyHash;
372
            final Document trustPath;
373
            if (agentAccount != null) {
×
374
                agentId = agentAccount.getString("agent");
×
375
                Validate.notNull(agentId);
×
376
                pubkeyHash = agentAccount.getString("pubkey");
×
377
                Validate.notNull(pubkeyHash);
×
378
                trustPath = getOne(s, "trustPaths_loading",
×
379
                        new Document("depth", depth)
×
380
                                .append("agent", agentId)
×
381
                                .append("pubkey", pubkeyHash)
×
382
                );
383
            } else {
384
                agentId = null;
×
385
                pubkeyHash = null;
×
386
                trustPath = null;
×
387
            }
388

389
            if (agentAccount == null) {
×
390
                schedule(s, FINISH_ITERATION.with("depth", depth).append("load-count", loadCount));
×
391
            } else if (trustPath == null) {
×
392
                // Account was seen but has no trust path at this depth; skip it
393
                set(s, "accounts_loading", agentAccount.append("status", skipped.getValue()));
×
394
                schedule(s, LOAD_CORE.with("depth", depth).append("load-count", loadCount));
×
395
            } else if (trustPath.getDouble("ratio") < MIN_TRUST_PATH_RATIO) {
×
396
                set(s, "accounts_loading", agentAccount.append("status", skipped.getValue()));
×
397
                Document d = new Document("pubkey", pubkeyHash).append("type", INTRO_TYPE_HASH);
×
398
                if (!has(s, "lists", d)) {
×
399
                    insert(s, "lists", d.append("status", encountered.getValue()));
×
400
                }
401
                schedule(s, LOAD_CORE.with("depth", depth).append("load-count", loadCount + 1));
×
402
            } else {
×
403
                // TODO check intro limit
404
                Document introList = new Document()
×
405
                        .append("pubkey", pubkeyHash)
×
406
                        .append("type", INTRO_TYPE_HASH)
×
407
                        .append("status", loading.getValue());
×
408
                if (!has(s, "lists", new Document("pubkey", pubkeyHash).append("type", INTRO_TYPE_HASH))) {
×
409
                    insert(s, "lists", introList);
×
410
                }
411

412
                try (var stream = NanopubLoader.retrieveNanopubsFromPeers(INTRO_TYPE_HASH, pubkeyHash)) {
×
413
                    stream.forEach(m -> {
×
414
                        if (!m.isSuccess())
×
415
                            throw new AbortingTaskException("Failed to download nanopub; aborting task...");
×
416
                        loadNanopub(s, m.getNanopub(), pubkeyHash, INTRO_TYPE);
×
417
                    });
×
418
                }
419

420
                set(s, "lists", introList.append("status", loaded.getValue()));
×
421

422
                // TODO check endorsement limit
423
                Document endorseList = new Document()
×
424
                        .append("pubkey", pubkeyHash)
×
425
                        .append("type", ENDORSE_TYPE_HASH)
×
426
                        .append("status", loading.getValue());
×
427
                if (!has(s, "lists", new Document("pubkey", pubkeyHash).append("type", ENDORSE_TYPE_HASH))) {
×
428
                    insert(s, "lists", endorseList);
×
429
                }
430

431
                try (var stream = NanopubLoader.retrieveNanopubsFromPeers(ENDORSE_TYPE_HASH, pubkeyHash)) {
×
432
                    stream.forEach(m -> {
×
433
                        if (!m.isSuccess())
×
434
                            throw new AbortingTaskException("Failed to download nanopub; aborting task...");
×
435
                        Nanopub nanopub = m.getNanopub();
×
436
                        loadNanopub(s, nanopub, pubkeyHash, ENDORSE_TYPE);
×
437
                        String sourceNpId = TrustyUriUtils.getArtifactCode(nanopub.getUri().stringValue());
×
438
                        Validate.notNull(sourceNpId);
×
439
                        for (Statement st : nanopub.getAssertion()) {
×
440
                            if (!st.getPredicate().equals(Utils.APPROVES_OF)) continue;
×
441
                            if (!(st.getObject() instanceof IRI)) continue;
×
442
                            if (!agentId.equals(st.getSubject().stringValue())) continue;
×
443
                            String objStr = st.getObject().stringValue();
×
444
                            if (!TrustyUriUtils.isPotentialTrustyUri(objStr)) continue;
×
445
                            String endorsedNpId = TrustyUriUtils.getArtifactCode(objStr);
×
446
                            Validate.notNull(endorsedNpId);
×
447
                            Document endorsement = new Document("agent", agentId)
×
448
                                    .append("pubkey", pubkeyHash)
×
449
                                    .append("endorsedNanopub", endorsedNpId)
×
450
                                    .append("source", sourceNpId);
×
451
                            if (!has(s, "endorsements_loading", endorsement)) {
×
452
                                insert(s, "endorsements_loading",
×
453
                                        endorsement.append("status", toRetrieve.getValue()));
×
454
                            }
455
                        }
×
456
                    });
×
457
                }
458

459
                set(s, "lists", endorseList.append("status", loaded.getValue()));
×
460

461
                Document df = new Document("pubkey", pubkeyHash).append("type", "$");
×
462
                if (!has(s, "lists", df)) insert(s, "lists",
×
463
                        df.append("status", encountered.getValue()));
×
464

465
                set(s, "accounts_loading", agentAccount.append("status", visited.getValue()));
×
466

467
                schedule(s, LOAD_CORE.with("depth", depth).append("load-count", loadCount + 1));
×
468
            }
469

470
        }
×
471

472
        // At the end of this step, we have added new endorsement
473
        // links to yet-to-retrieve agent introductions:
474
        // ------------------------------------------------------------
475
        //
476
        //         o      ----endorses----> [intro]
477
        //    --> /#\  /o\___            (to-retrieve)
478
        //        / \  \_/^^^
479
        //         (visited)
480
        //
481
        //    ========[X] trust path
482
        //
483
        // ------------------------------------------------------------
484
        // Only one endorsement is shown here, but there are typically
485
        // several.
486

487
    },
488

489
    FINISH_ITERATION {
33✔
490
        public void run(ClientSession s, Document taskDoc) {
491

492
            int depth = taskDoc.getInteger("depth");
×
493
            int loadCount = taskDoc.getInteger("load-count");
×
494

495
            if (loadCount == 0) {
×
496
                log.info("No new cores loaded; finishing iteration");
×
497
                schedule(s, CALCULATE_TRUST_SCORES);
×
498
            } else if (depth == MAX_TRUST_PATH_DEPTH) {
×
499
                log.info("Maximum depth reached: {}", depth);
×
500
                schedule(s, CALCULATE_TRUST_SCORES);
×
501
            } else {
502
                log.info("Progressing iteration at depth {}", depth + 1);
×
503
                schedule(s, LOAD_DECLARATIONS.with("depth", depth + 1));
×
504
            }
505

506
        }
×
507

508
    },
509

510
    CALCULATE_TRUST_SCORES {
33✔
511

512
        // DB read from: accounts, trustPaths
513
        // DB write to:  accounts
514

515
        public void run(ClientSession s, Document taskDoc) {
516

517
            Document d = getOne(s, "accounts_loading", new Document("status", expanded.getValue()));
×
518

519
            if (d == null) {
×
520
                schedule(s, AGGREGATE_AGENTS);
×
521
            } else {
522
                double ratio = 0.0;
×
523
                Map<String, Boolean> seenPathElements = new HashMap<>();
×
524
                int pathCount = 0;
×
525
                MongoCursor<Document> trustPaths = collection("trustPaths_loading").find(s,
×
526
                        new Document("agent", d.get("agent").toString()).append("pubkey", d.get("pubkey").toString())
×
527
                ).sort(orderBy(ascending("depth"), descending("ratio"), ascending("sorthash"))).cursor();
×
528
                while (trustPaths.hasNext()) {
×
529
                    Document trustPath = trustPaths.next();
×
530
                    ratio += trustPath.getDouble("ratio");
×
531
                    boolean independentPath = true;
×
532
                    String[] pathElements = trustPath.getString("_id").split(" ");
×
533
                    // Iterate over path elements, ignoring first (root) and last (this agent/pubkey):
534
                    for (int i = 1; i < pathElements.length - 1; i++) {
×
535
                        String p = pathElements[i];
×
536
                        if (seenPathElements.containsKey(p)) {
×
537
                            independentPath = false;
×
538
                            break;
×
539
                        }
540
                        seenPathElements.put(p, true);
×
541
                    }
542
                    if (independentPath) pathCount += 1;
×
543
                }
×
544
                double rawQuota = GLOBAL_QUOTA * ratio;
×
545
                int quota = (int) rawQuota;
×
546
                if (rawQuota < MIN_USER_QUOTA) {
×
547
                    quota = MIN_USER_QUOTA;
×
548
                } else if (rawQuota > MAX_USER_QUOTA) {
×
549
                    quota = MAX_USER_QUOTA;
×
550
                }
551
                set(s, "accounts_loading",
×
552
                        d.append("status", processed.getValue())
×
553
                                .append("ratio", ratio)
×
554
                                .append("pathCount", pathCount)
×
555
                                .append("quota", quota)
×
556
                );
557
                schedule(s, CALCULATE_TRUST_SCORES);
×
558
            }
559

560
        }
×
561

562
    },
563

564
    AGGREGATE_AGENTS {
33✔
565

566
        // DB read from: accounts, agents
567
        // DB write to:  accounts, agents
568

569
        public void run(ClientSession s, Document taskDoc) {
570

571
            Document a = getOne(s, "accounts_loading", new Document("status", processed.getValue()));
×
572
            if (a == null) {
×
573
                schedule(s, ASSIGN_PUBKEYS);
×
574
            } else {
575
                Document agentId = new Document("agent", a.get("agent").toString()).append("status", processed.getValue());
×
576
                int count = 0;
×
577
                int pathCountSum = 0;
×
578
                double totalRatio = 0.0d;
×
579
                MongoCursor<Document> agentAccounts = collection("accounts_loading").find(s, agentId).cursor();
×
580
                while (agentAccounts.hasNext()) {
×
581
                    Document d = agentAccounts.next();
×
582
                    count++;
×
583
                    pathCountSum += d.getInteger("pathCount");
×
584
                    totalRatio += d.getDouble("ratio");
×
585
                }
×
586
                collection("accounts_loading").updateMany(s, agentId, new Document("$set",
×
587
                        new DbEntryWrapper(aggregated).getDocument()));
×
588
                insert(s, "agents_loading",
×
589
                        agentId.append("accountCount", count)
×
590
                                .append("avgPathCount", (double) pathCountSum / count)
×
591
                                .append("totalRatio", totalRatio)
×
592
                );
593
                schedule(s, AGGREGATE_AGENTS);
×
594
            }
595

596
        }
×
597

598
    },
599

600
    ASSIGN_PUBKEYS {
33✔
601

602
        // DB read from: accounts
603
        // DB write to:  accounts
604

605
        public void run(ClientSession s, Document taskDoc) {
606

607
            Document a = getOne(s, "accounts_loading", new DbEntryWrapper(aggregated).getDocument());
×
608
            if (a == null) {
×
609
                schedule(s, DETERMINE_UPDATES);
×
610
            } else {
611
                Document pubkeyId = new Document("pubkey", a.get("pubkey").toString());
×
612
                if (collection("accounts_loading").countDocuments(s, pubkeyId) == 1) {
×
613
                    collection("accounts_loading").updateMany(s, pubkeyId,
×
614
                            new Document("$set", new DbEntryWrapper(approved).getDocument()));
×
615
                } else {
616
                    // TODO At the moment all get marked as 'contested'; implement more nuanced algorithm
617
                    collection("accounts_loading").updateMany(s, pubkeyId, new Document("$set",
×
618
                            new DbEntryWrapper(contested).getDocument()));
×
619
                }
620
                schedule(s, ASSIGN_PUBKEYS);
×
621
            }
622

623
        }
×
624

625
    },
626

627
    DETERMINE_UPDATES {
33✔
628

629
        // DB read from: accounts
630
        // DB write to:  accounts
631

632
        public void run(ClientSession s, Document taskDoc) {
633

634
            // TODO Handle contested accounts properly:
635
            for (Document d : collection("accounts_loading").find(
×
636
                    new DbEntryWrapper(approved).getDocument())) {
×
637
                // TODO Consider quota too:
638
                Document accountId = new Document("agent", d.get("agent").toString()).append("pubkey", d.get("pubkey").toString());
×
639
                if (collection(Collection.ACCOUNTS.toString()) == null || !has(s, Collection.ACCOUNTS.toString(),
×
640
                        accountId.append("status", loaded.getValue()))) {
×
641
                    set(s, "accounts_loading", d.append("status", toLoad.getValue()));
×
642
                } else {
643
                    set(s, "accounts_loading", d.append("status", loaded.getValue()));
×
644
                }
645
            }
×
646
            schedule(s, FINALIZE_TRUST_STATE);
×
647

648
        }
×
649

650
    },
651

652
    FINALIZE_TRUST_STATE {
33✔
653
        // We do this is a separate task/transaction, because if we do it at the beginning of RELEASE_DATA, that task hangs and cannot
654
        // properly re-run (as some renaming outside of transactions will have taken place).
655
        public void run(ClientSession s, Document taskDoc) {
656
            String newTrustStateHash = RegistryDB.calculateTrustStateHash(s);
×
657
            String previousTrustStateHash = (String) getValue(s, Collection.SERVER_INFO.toString(), "trustStateHash");  // may be null
×
658
            setValue(s, Collection.SERVER_INFO.toString(), "lastTrustStateUpdate", ZonedDateTime.now().toString());
×
659

660
            schedule(s, RELEASE_DATA.with("newTrustStateHash", newTrustStateHash).append("previousTrustStateHash", previousTrustStateHash));
×
661
        }
×
662

663
    },
664

665
    RELEASE_DATA {
33✔
666
        public void run(ClientSession s, Document taskDoc) {
667
            ServerStatus status = getServerStatus(s);
×
668

669
            String newTrustStateHash = taskDoc.get("newTrustStateHash").toString();
×
670
            String previousTrustStateHash = taskDoc.getString("previousTrustStateHash");  // may be null
×
671

672
            // Renaming collections is run outside of a transaction, but is idempotent operation, so can safely be retried if task fails:
673
            rename("accounts_loading", Collection.ACCOUNTS.toString());
×
674
            rename("trustPaths_loading", "trustPaths");
×
675
            rename("agents_loading", Collection.AGENTS.toString());
×
676
            rename("endorsements_loading", "endorsements");
×
677

678
            if (previousTrustStateHash == null || !previousTrustStateHash.equals(newTrustStateHash)) {
×
679
                increaseStateCounter(s);
×
680
                setValue(s, Collection.SERVER_INFO.toString(), "trustStateHash", newTrustStateHash);
×
681
                insert(s, "debug_trustPaths", new Document()
×
682
                        .append("trustStateTxt", DebugPage.getTrustPathsTxt(s))
×
683
                        .append("trustStateHash", newTrustStateHash)
×
684
                        .append("trustStateCounter", getValue(s, Collection.SERVER_INFO.toString(), "trustStateCounter"))
×
685
                );
686
            }
687

688
            if (status == coreLoading) {
×
689
                setServerStatus(s, coreReady);
×
690
            } else {
691
                setServerStatus(s, ready);
×
692
            }
693

694
            // Run update after 1h:
695
            schedule(s, UPDATE.withDelay(60 * 60 * 1000));
×
696
        }
×
697

698
    },
699

700
    UPDATE {
33✔
701
        public void run(ClientSession s, Document taskDoc) {
702
            ServerStatus status = getServerStatus(s);
×
703
            if (status == ready || status == coreReady) {
×
704
                setServerStatus(s, updating);
×
705
                schedule(s, INIT_COLLECTIONS);
×
706
            } else {
707
                log.info("Postponing update; currently in status {}", status);
×
708
                schedule(s, UPDATE.withDelay(10 * 60 * 1000));
×
709
            }
710

711
        }
×
712

713
    },
714

715
    LOAD_FULL {
33✔
716
        public void run(ClientSession s, Document taskDoc) {
717
            if ("false".equals(System.getenv("REGISTRY_PERFORM_FULL_LOAD"))) return;
15!
718

719
            ServerStatus status = getServerStatus(s);
9✔
720
            if (status != coreReady && status != ready && status != updating) {
27!
721
                log.info("Server currently not ready; checking again later");
9✔
722
                schedule(s, LOAD_FULL.withDelay(60 * 1000));
15✔
723
                return;
3✔
724
            }
725

726
            Document a = getOne(s, Collection.ACCOUNTS.toString(), new DbEntryWrapper(toLoad).getDocument());
×
727
            if (a == null) {
×
728
                log.info("Nothing to load");
×
729
                if (status == coreReady) {
×
730
                    log.info("Full load finished");
×
731
                    setServerStatus(s, ready);
×
732
                }
733
                log.info("Scheduling optional loading checks");
×
734
                schedule(s, RUN_OPTIONAL_LOAD.withDelay(100));
×
735
            } else {
736
                final String ph = a.getString("pubkey");
×
737
                if (!ph.equals("$")) {
×
738
                    try (var stream = NanopubLoader.retrieveNanopubsFromPeers("$", ph)) {
×
739
                        long startTime = System.nanoTime();
×
740
                        AtomicLong loaded = new AtomicLong(0);
×
741
                        stream.forEach(m -> {
×
742
                            if (!m.isSuccess())
×
743
                                throw new AbortingTaskException("Failed to download nanopub; aborting task...");
×
744
                            loadNanopub(s, m.getNanopub(), ph, "$");
×
745
                            loaded.incrementAndGet();
×
746
                        });
×
747
                        double timeSeconds = (System.nanoTime() - startTime) * 1e-9;
×
748
                        log.info("Loaded {} nanopubs in {}s, {} np/s",
×
749
                                loaded.get(), timeSeconds, String.format("%.2f", loaded.get() / timeSeconds));
×
750
                    }
751
                }
752

753
                Document l = getOne(s, "lists", new Document().append("pubkey", ph).append("type", "$"));
×
754
                if (l != null) set(s, "lists", l.append("status", loaded.getValue()));
×
755
                set(s, Collection.ACCOUNTS.toString(), a.append("status", loaded.getValue()));
×
756

757
                schedule(s, LOAD_FULL.withDelay(100));
×
758
            }
759
        }
×
760

761
        @Override
762
        public boolean runAsTransaction() {
763
            // TODO Make this a transaction once we connect to other Nanopub Registry instances:
764
            return false;
×
765
        }
766

767
    },
768

769
    RUN_OPTIONAL_LOAD {
33✔
770
        public void run(ClientSession s, Document taskDoc) {
771
            Document di = getOne(s, "lists", new Document("type", INTRO_TYPE_HASH).append("status", encountered.getValue()));
×
772
            if (di != null) {
×
773
                final String pubkeyHash = di.getString("pubkey");
×
774
                Validate.notNull(pubkeyHash);
×
775
                log.info("Optional core loading: {}", pubkeyHash);
×
776

777
                try (var stream = NanopubLoader.retrieveNanopubsFromPeers(INTRO_TYPE_HASH, pubkeyHash)) {
×
778
                    stream.forEach(m -> {
×
779
                        if (!m.isSuccess())
×
780
                            throw new AbortingTaskException("Failed to download nanopub; aborting task...");
×
781
                        loadNanopub(s, m.getNanopub(), pubkeyHash, INTRO_TYPE);
×
782
                    });
×
783
                }
784
                set(s, "lists", di.append("status", loaded.getValue()));
×
785

786
                try (var stream = NanopubLoader.retrieveNanopubsFromPeers(ENDORSE_TYPE_HASH, pubkeyHash)) {
×
787
                    stream.forEach(m -> {
×
788
                        if (!m.isSuccess())
×
789
                            throw new AbortingTaskException("Failed to download nanopub; aborting task...");
×
790
                        loadNanopub(s, m.getNanopub(), pubkeyHash, ENDORSE_TYPE);
×
791
                    });
×
792
                }
793

794
                Document de = new Document("pubkey", pubkeyHash).append("type", ENDORSE_TYPE_HASH);
×
795
                if (has(s, "lists", de)) {
×
796
                    set(s, "lists", de.append("status", loaded.getValue()));
×
797
                } else {
798
                    insert(s, "lists", de.append("status", loaded.getValue()));
×
799
                }
800

801
                Document df = new Document("pubkey", pubkeyHash).append("type", "$");
×
802
                if (!has(s, "lists", df)) insert(s, "lists", df.append("status", encountered.getValue()));
×
803

804
                if (prioritizeAllPubkeys()) {
×
805
                    schedule(s, RUN_OPTIONAL_LOAD.withDelay(100));
×
806
                } else {
807
                    schedule(s, CHECK_NEW.withDelay(500));
×
808
                }
809
                return;
×
810
            }
811

812
            Document df = getOne(s, "lists", new Document("type", "$").append("status", encountered.getValue()));
×
813
            if (df != null) {
×
814
                final String pubkeyHash = df.getString("pubkey");
×
815
                log.info("Optional full loading: {}", pubkeyHash);
×
816

817
                try (var stream = NanopubLoader.retrieveNanopubsFromPeers("$", pubkeyHash)) {
×
818
                    stream.forEach(m -> {
×
819
                        if (!m.isSuccess())
×
820
                            throw new AbortingTaskException("Failed to download nanopub; aborting task...");
×
821
                        loadNanopub(s, m.getNanopub(), pubkeyHash, "$");
×
822
                    });
×
823
                }
824

825
                set(s, "lists", df.append("status", loaded.getValue()));
×
826

827
                if (prioritizeAllPubkeys()) {
×
828
                    schedule(s, RUN_OPTIONAL_LOAD.withDelay(100));
×
829
                    return;
×
830
                }
831
            }
832

833
            schedule(s, CHECK_NEW.withDelay(500));
×
834
        }
×
835

836
    },
837

838
    CHECK_NEW {
33✔
839
        public void run(ClientSession s, Document taskDoc) {
840
            RegistryPeerConnector.checkPeers(s);
×
841
            // Keep legacy connection during transition period:
842
            LegacyConnector.checkForNewNanopubs(s);
×
843
            // TODO Somehow throttle the loading of such potentially non-approved nanopubs
844

845
            schedule(s, LOAD_FULL.withDelay(100));
×
846
        }
×
847

848
        @Override
849
        public boolean runAsTransaction() {
850
            // Peer sync includes long-running streaming fetches that would exceed
851
            // MongoDB's transaction timeout; each operation is individually safe.
852
            return false;
×
853
        }
854

855
    };
856

857
    private static final Logger log = LoggerFactory.getLogger(Task.class);
9✔
858

859
    public abstract void run(ClientSession s, Document taskDoc) throws Exception;
860

861
    public boolean runAsTransaction() {
862
        return true;
×
863
    }
864

865
    Document asDocument() {
866
        return withDelay(0L);
12✔
867
    }
868

869
    private Document withDelay(long delay) {
870
        // TODO Rename "not-before" to "notBefore" for consistency with other field names
871
        return new Document()
15✔
872
                .append("not-before", System.currentTimeMillis() + delay)
21✔
873
                .append("action", name());
6✔
874
    }
875

876
    private Document with(String key, Object value) {
877
        return asDocument().append(key, value);
×
878
    }
879

880
    private static boolean prioritizeAllPubkeys() {
881
        return "true".equals(System.getenv("REGISTRY_PRIORITIZE_ALL_PUBKEYS"));
×
882
    }
883

884
    // TODO Move these to setting:
885
    private static final int MAX_TRUST_PATH_DEPTH = 10;
886
    private static final double MIN_TRUST_PATH_RATIO = 0.00000001;
887
    //private static final double MIN_TRUST_PATH_RATIO = 0.01; // For testing
888
    private static final int GLOBAL_QUOTA = 100000000;
889
    private static final int MIN_USER_QUOTA = 100;
890
    private static final int MAX_USER_QUOTA = 10000;
891

892
    private static MongoCollection<Document> tasksCollection = collection(Collection.TASKS.toString());
15✔
893

894
    private static volatile String currentTaskName;
895
    private static volatile long currentTaskStartTime;
896

897
    public static String getCurrentTaskName() {
898
        return currentTaskName;
×
899
    }
900

901
    public static long getCurrentTaskStartTime() {
902
        return currentTaskStartTime;
×
903
    }
904

905
    /**
906
     * The super important base entry point!
907
     */
908
    static void runTasks() {
909
        try (ClientSession s = RegistryDB.getClient().startSession()) {
×
910
            if (!RegistryDB.isInitialized(s)) {
×
911
                schedule(s, INIT_DB); // does not yet execute, only schedules
×
912
            }
913

914
            while (true) {
915
                FindIterable<Document> taskResult = tasksCollection.find(s).sort(ascending("not-before"));
×
916
                Document taskDoc = taskResult.first();
×
917
                long sleepTime = 10;
×
918
                if (taskDoc != null && taskDoc.getLong("not-before") < System.currentTimeMillis()) {
×
919
                    Task task = valueOf(taskDoc.getString("action"));
×
920
                    log.info("Running task: {}", task.name());
×
921
                    if (task.runAsTransaction()) {
×
922
                        try {
923
                            s.startTransaction();
×
924
                            log.info("Transaction started");
×
925
                            runTask(task, taskDoc);
×
926
                            s.commitTransaction();
×
927
                            log.info("Transaction committed");
×
928
                        } catch (Exception ex) {
×
929
                            log.info("Aborting transaction", ex);
×
930
                            abortTransaction(s, ex.getMessage());
×
931
                            log.info("Transaction aborted");
×
932
                            sleepTime = 1000;
×
933
                        } finally {
934
                            cleanTransactionWithRetry(s);
×
935
                        }
×
936
                    } else {
937
                        try {
938
                            runTask(task, taskDoc);
×
939
                        } catch (Exception ex) {
×
940
                            log.info("Transaction failed", ex);
×
941
                        }
×
942
                    }
943
                }
944
                try {
945
                    Thread.sleep(sleepTime);
×
946
                } catch (InterruptedException ex) {
×
947
                    // ignore
948
                }
×
949
            }
×
950
        }
951
    }
952

953
    static void runTask(Task task, Document taskDoc) throws Exception {
954
        try (ClientSession s = RegistryDB.getClient().startSession()) {
9✔
955
            log.info("Executing task: {}", task.name());
15✔
956
            currentTaskName = task.name();
9✔
957
            currentTaskStartTime = System.currentTimeMillis();
6✔
958
            task.run(s, taskDoc);
12✔
959
            tasksCollection.deleteOne(s, eq("_id", taskDoc.get("_id")));
27✔
960
            log.info("Task {} completed and removed from queue.", task.name());
15✔
961
        } finally {
962
            currentTaskName = null;
6✔
963
        }
964
    }
3✔
965

966
    public static void abortTransaction(ClientSession mongoSession, String message) {
967
        boolean successful = false;
×
968
        while (!successful) {
×
969
            try {
970
                if (mongoSession.hasActiveTransaction()) {
×
971
                    mongoSession.abortTransaction();
×
972
                }
973
                successful = true;
×
974
            } catch (Exception ex) {
×
975
                log.info("Aborting transaction failed. ", ex);
×
976
                try {
977
                    Thread.sleep(1000);
×
978
                } catch (InterruptedException iex) {
×
979
                    // ignore
980
                }
×
981
            }
×
982
        }
983
    }
×
984

985
    public synchronized static void cleanTransactionWithRetry(ClientSession mongoSession) {
986
        boolean successful = false;
×
987
        while (!successful) {
×
988
            try {
989
                if (mongoSession.hasActiveTransaction()) {
×
990
                    mongoSession.abortTransaction();
×
991
                }
992
                successful = true;
×
993
            } catch (Exception ex) {
×
994
                log.info("Cleaning transaction failed. ", ex);
×
995
                try {
996
                    Thread.sleep(1000);
×
997
                } catch (InterruptedException iex) {
×
998
                    // ignore
999
                }
×
1000
            }
×
1001
        }
1002
    }
×
1003

1004
    private static IntroNanopub getAgentIntro(ClientSession mongoSession, String nanopubId) {
1005
        IntroNanopub agentIntro = new IntroNanopub(NanopubLoader.retrieveNanopub(mongoSession, nanopubId));
×
1006
        if (agentIntro.getUser() == null) return null;
×
1007
        loadNanopub(mongoSession, agentIntro.getNanopub());
×
1008
        return agentIntro;
×
1009
    }
1010

1011
    private static void setServerStatus(ClientSession mongoSession, ServerStatus status) {
1012
        setValue(mongoSession, Collection.SERVER_INFO.toString(), "status", status.toString());
21✔
1013
    }
3✔
1014

1015
    private static ServerStatus getServerStatus(ClientSession mongoSession) {
1016
        Object status = getValue(mongoSession, Collection.SERVER_INFO.toString(), "status");
18✔
1017
        if (status == null) {
6!
1018
            throw new RuntimeException("Illegal DB state: serverInfo status unavailable");
×
1019
        }
1020
        return ServerStatus.valueOf(status.toString());
12✔
1021
    }
1022

1023
    private static void schedule(ClientSession mongoSession, Task task) {
1024
        schedule(mongoSession, task.asDocument());
12✔
1025
    }
3✔
1026

1027
    private static void schedule(ClientSession mongoSession, Document taskDoc) {
1028
        log.info("Scheduling task: {}", taskDoc.getString("action"));
18✔
1029
        tasksCollection.insertOne(mongoSession, taskDoc);
12✔
1030
    }
3✔
1031

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