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

knowledgepixels / nanopub-registry / 21252662344

22 Jan 2026 02:44PM UTC coverage: 21.253% (+2.3%) from 18.999%
21252662344

push

github

ashleycaselli
refactor(tests): simplify environment setup and clear static fields in test classes

97 of 586 branches covered (16.55%)

Branch coverage included in aggregate %.

405 of 1776 relevant lines covered (22.8%)

4.23 hits per line

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

6.74
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) {
×
54
                throw new IllegalTaskStatusException("Illegal status for this task: " + getServerStatus(s));
×
55
            }
56

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

66
    },
67

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

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

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

90
            setServerStatus(s, coreLoading);
×
91
            schedule(s, INIT_COLLECTIONS);
×
92
        }
×
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 (trustPath == null) {
×
390
                schedule(s, FINISH_ITERATION.with("depth", depth).append("load-count", loadCount));
×
391
            } else if (trustPath.getDouble("ratio") < MIN_TRUST_PATH_RATIO) {
×
392
                set(s, "accounts_loading", agentAccount.append("status", skipped.getValue()));
×
393
                Document d = new Document("pubkey", pubkeyHash).append("type", INTRO_TYPE_HASH);
×
394
                if (!has(s, "lists", d)) {
×
395
                    insert(s, "lists", d.append("status", encountered.getValue()));
×
396
                }
397
                schedule(s, LOAD_CORE.with("depth", depth).append("load-count", loadCount + 1));
×
398
            } else {
×
399
                // TODO check intro limit
400
                Document introList = new Document()
×
401
                        .append("pubkey", pubkeyHash)
×
402
                        .append("type", INTRO_TYPE_HASH)
×
403
                        .append("status", loading.getValue());
×
404
                if (!has(s, "lists", new Document("pubkey", pubkeyHash).append("type", INTRO_TYPE_HASH))) {
×
405
                    insert(s, "lists", introList);
×
406
                }
407

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

416
                set(s, "lists", introList.append("status", loaded.getValue()));
×
417

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

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

455
                set(s, "lists", endorseList.append("status", loaded.getValue()));
×
456

457
                Document df = new Document("pubkey", pubkeyHash).append("type", "$");
×
458
                if (!has(s, "lists", df)) insert(s, "lists",
×
459
                        df.append("status", encountered.getValue()));
×
460

461
                set(s, "accounts_loading", agentAccount.append("status", visited.getValue()));
×
462

463
                schedule(s, LOAD_CORE.with("depth", depth).append("load-count", loadCount + 1));
×
464
            }
465

466
        }
×
467

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

483
    },
484

485
    FINISH_ITERATION {
33✔
486
        public void run(ClientSession s, Document taskDoc) {
487

488
            int depth = taskDoc.getInteger("depth");
×
489
            int loadCount = taskDoc.getInteger("load-count");
×
490

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

502
        }
×
503

504
    },
505

506
    CALCULATE_TRUST_SCORES {
33✔
507

508
        // DB read from: accounts, trustPaths
509
        // DB write to:  accounts
510

511
        public void run(ClientSession s, Document taskDoc) {
512

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

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

556
        }
×
557

558
    },
559

560
    AGGREGATE_AGENTS {
33✔
561

562
        // DB read from: accounts, agents
563
        // DB write to:  accounts, agents
564

565
        public void run(ClientSession s, Document taskDoc) {
566

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

592
        }
×
593

594
    },
595

596
    ASSIGN_PUBKEYS {
33✔
597

598
        // DB read from: accounts
599
        // DB write to:  accounts
600

601
        public void run(ClientSession s, Document taskDoc) {
602

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

619
        }
×
620

621
    },
622

623
    DETERMINE_UPDATES {
33✔
624

625
        // DB read from: accounts
626
        // DB write to:  accounts
627

628
        public void run(ClientSession s, Document taskDoc) {
629

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

644
        }
×
645

646
    },
647

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

656
            schedule(s, RELEASE_DATA.with("newTrustStateHash", newTrustStateHash).append("previousTrustStateHash", previousTrustStateHash));
×
657
        }
×
658

659
    },
660

661
    RELEASE_DATA {
33✔
662
        public void run(ClientSession s, Document taskDoc) {
663
            ServerStatus status = getServerStatus(s);
×
664

665
            String newTrustStateHash = taskDoc.get("newTrustStateHash").toString();
×
666
            String previousTrustStateHash = taskDoc.getString("previousTrustStateHash");  // may be null
×
667

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

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

684
            if (status == coreLoading) {
×
685
                setServerStatus(s, coreReady);
×
686
            } else {
687
                setServerStatus(s, ready);
×
688
            }
689

690
            // Run update after 1h:
691
            schedule(s, UPDATE.withDelay(60 * 60 * 1000));
×
692
        }
×
693

694
    },
695

696
    UPDATE {
33✔
697
        public void run(ClientSession s, Document taskDoc) {
698

699
            ServerStatus status = getServerStatus(s);
×
700
            if (status == ready || status == coreReady) {
×
701
                setServerStatus(s, updating);
×
702
                schedule(s, INIT_COLLECTIONS);
×
703
            } else {
704
                log.info("Postponing update; currently in status {}", status);
×
705
                schedule(s, UPDATE.withDelay(10 * 60 * 1000));
×
706
            }
707

708
        }
×
709

710
    },
711

712
    LOAD_FULL {
33✔
713
        public void run(ClientSession s, Document taskDoc) {
714
            if ("false".equals(System.getenv("REGISTRY_PERFORM_FULL_LOAD"))) return;
×
715

716
            ServerStatus status = getServerStatus(s);
×
717
            if (status != coreReady && status != ready) {
×
718
                log.info("Server currently not ready; checking again later");
×
719
                schedule(s, LOAD_FULL.withDelay(60 * 1000));
×
720
                return;
×
721
            }
722

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

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

754
                schedule(s, LOAD_FULL.withDelay(100));
×
755
            }
756
        }
×
757

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

764
    },
765

766
    CHECK_MORE_PUBKEYS {
33✔
767
        public void run(ClientSession s, Document taskDoc) {
768
            try {
769
                for (String pubkeyHash : Utils.retrieveListFromJsonUrl(Utils.getRandomPeer() + "pubkeys.json")) {
×
770
                    Validate.notNull(pubkeyHash);
×
771
                    Document d = new Document("pubkey", pubkeyHash).append("type", INTRO_TYPE_HASH);
×
772
                    if (!has(s, "lists", d)) {
×
773
                        insert(s, "lists", d.append("status", encountered.getValue()));
×
774
                    }
775
                }
×
776
            } catch (Exception ex) {
×
777
                throw new RuntimeException(ex);
×
778
            }
×
779

780
            schedule(s, RUN_OPTIONAL_LOAD.withDelay(100));
×
781
        }
×
782

783
    },
784

785
    RUN_OPTIONAL_LOAD {
33✔
786
        public void run(ClientSession s, Document taskDoc) {
787
            Document di = getOne(s, "lists", new Document("type", INTRO_TYPE_HASH).append("status", encountered.getValue()));
×
788
            if (di != null) {
×
789
                final String pubkeyHash = di.getString("pubkey");
×
790
                Validate.notNull(pubkeyHash);
×
791
                log.info("Optional core loading: {}", pubkeyHash);
×
792

793
                try (var stream = NanopubLoader.retrieveNanopubsFromPeers(INTRO_TYPE_HASH, pubkeyHash)) {
×
794
                    stream.forEach(m -> {
×
795
                        if (!m.isSuccess())
×
796
                            throw new AbortingTaskException("Failed to download nanopub; aborting task...");
×
797
                        loadNanopub(s, m.getNanopub(), pubkeyHash, INTRO_TYPE);
×
798
                    });
×
799
                }
800
                set(s, "lists", di.append("status", loaded.getValue()));
×
801

802
                try (var stream = NanopubLoader.retrieveNanopubsFromPeers(ENDORSE_TYPE_HASH, pubkeyHash)) {
×
803
                    stream.forEach(m -> {
×
804
                        if (!m.isSuccess())
×
805
                            throw new AbortingTaskException("Failed to download nanopub; aborting task...");
×
806
                        loadNanopub(s, m.getNanopub(), pubkeyHash, ENDORSE_TYPE);
×
807
                    });
×
808
                }
809

810
                Document de = new Document("pubkey", pubkeyHash).append("type", ENDORSE_TYPE_HASH);
×
811
                if (has(s, "lists", de)) {
×
812
                    set(s, "lists", de.append("status", loaded.getValue()));
×
813
                } else {
814
                    insert(s, "lists", de.append("status", loaded.getValue()));
×
815
                }
816

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

820
                schedule(s, CHECK_NEW.withDelay(100));
×
821
                return;
×
822
            }
823

824
            Document df = getOne(s, "lists", new Document("type", "$").append("status", encountered.getValue()));
×
825
            if (df != null) {
×
826
                final String pubkeyHash = df.getString("pubkey");
×
827
                log.info("Optional full loading: {}", pubkeyHash);
×
828

829
                try (var stream = NanopubLoader.retrieveNanopubsFromPeers("$", pubkeyHash)) {
×
830
                    stream.forEach(m -> {
×
831
                        if (!m.isSuccess())
×
832
                            throw new AbortingTaskException("Failed to download nanopub; aborting task...");
×
833
                        loadNanopub(s, m.getNanopub(), pubkeyHash, "$");
×
834
                    });
×
835
                }
836

837
                set(s, "lists", df.append("status", loaded.getValue()));
×
838
            }
839

840
            schedule(s, CHECK_NEW.withDelay(100));
×
841
        }
×
842

843
    },
844

845
    CHECK_NEW {
33✔
846
        public void run(ClientSession s, Document taskDoc) {
847
            // TODO Replace this legacy connection with checks at other Nanopub Registries:
848
            LegacyConnector.checkForNewNanopubs(s);
×
849
            // TODO Somehow throttle the loading of such potentially non-approved nanopubs
850

851
            schedule(s, LOAD_FULL.withDelay(100));
×
852
        }
×
853

854
    };
855

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

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

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

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

868
    private Document withDelay(long delay) {
869
        return new Document()
15✔
870
                .append("not-before", System.currentTimeMillis() + delay)
21✔
871
                .append("action", name());
6✔
872
    }
873

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

878
    // TODO Move these to setting:
879
    private static final int MAX_TRUST_PATH_DEPTH = 10;
880
    private static final double MIN_TRUST_PATH_RATIO = 0.00000001;
881
    //private static final double MIN_TRUST_PATH_RATIO = 0.01; // For testing
882
    private static final int GLOBAL_QUOTA = 100000000;
883
    private static final int MIN_USER_QUOTA = 100;
884
    private static final int MAX_USER_QUOTA = 10000;
885

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

888
    /**
889
     * The super important base entry point!
890
     */
891
    static void runTasks() {
892
        try (ClientSession s = RegistryDB.getClient().startSession()) {
×
893
            if (!RegistryDB.isInitialized(s)) {
×
894
                schedule(s, INIT_DB); // does not yet execute, only schedules
×
895
            }
896

897
            while (true) {
898
                FindIterable<Document> taskResult = tasksCollection.find(s).sort(ascending("not-before"));
×
899
                Document taskDoc = taskResult.first();
×
900
                long sleepTime = 10;
×
901
                if (taskDoc != null && taskDoc.getLong("not-before") < System.currentTimeMillis()) {
×
902
                    Task task = valueOf(taskDoc.getString("action"));
×
903
                    log.info("Running task: {}", task.name());
×
904
                    if (task.runAsTransaction()) {
×
905
                        try {
906
                            s.startTransaction();
×
907
                            log.info("Transaction started");
×
908
                            runTask(task, taskDoc);
×
909
                            s.commitTransaction();
×
910
                            log.info("Transaction committed");
×
911
                        } catch (Exception ex) {
×
912
                            log.info("Aborting transaction", ex);
×
913
                            abortTransaction(s, ex.getMessage());
×
914
                            log.info("Transaction aborted");
×
915
                            sleepTime = 1000;
×
916
                        } finally {
917
                            cleanTransactionWithRetry(s);
×
918
                        }
×
919
                    } else {
920
                        try {
921
                            runTask(task, taskDoc);
×
922
                        } catch (Exception ex) {
×
923
                            log.info("Transaction failed", ex);
×
924
                        }
×
925
                    }
926
                }
927
                try {
928
                    Thread.sleep(sleepTime);
×
929
                } catch (InterruptedException ex) {
×
930
                    // ignore
931
                }
×
932
            }
×
933
        }
934
    }
935

936
    static void runTask(Task task, Document taskDoc) throws Exception {
937
        try (ClientSession s = RegistryDB.getClient().startSession()) {
9✔
938
            log.info("Executing task: {}", task.name());
15✔
939
            task.run(s, taskDoc);
12✔
940
            tasksCollection.deleteOne(s, eq("_id", taskDoc.get("_id")));
27✔
941
            log.info("Task {} completed and removed from queue.", task.name());
15✔
942
        }
943
    }
3✔
944

945
    public static void abortTransaction(ClientSession mongoSession, String message) {
946
        boolean successful = false;
×
947
        while (!successful) {
×
948
            try {
949
                if (mongoSession.hasActiveTransaction()) {
×
950
                    mongoSession.abortTransaction();
×
951
                }
952
                successful = true;
×
953
            } catch (Exception ex) {
×
954
                log.info("Aborting transaction failed. ", ex);
×
955
                try {
956
                    Thread.sleep(1000);
×
957
                } catch (InterruptedException iex) {
×
958
                    // ignore
959
                }
×
960
            }
×
961
        }
962
    }
×
963

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

983
    private static IntroNanopub getAgentIntro(ClientSession mongoSession, String nanopubId) {
984
        IntroNanopub agentIntro = new IntroNanopub(NanopubLoader.retrieveNanopub(mongoSession, nanopubId));
×
985
        if (agentIntro.getUser() == null) return null;
×
986
        loadNanopub(mongoSession, agentIntro.getNanopub());
×
987
        return agentIntro;
×
988
    }
989

990
    private static void setServerStatus(ClientSession mongoSession, ServerStatus status) {
991
        setValue(mongoSession, Collection.SERVER_INFO.toString(), "status", status.toString());
21✔
992
    }
3✔
993

994
    private static ServerStatus getServerStatus(ClientSession mongoSession) {
995
        Object status = getValue(mongoSession, Collection.SERVER_INFO.toString(), "status");
×
996
        if (status == null) {
×
997
            throw new RuntimeException("Illegal DB state: serverInfo status unavailable");
×
998
        }
999
        return ServerStatus.valueOf(status.toString());
×
1000
    }
1001

1002
    private static void schedule(ClientSession mongoSession, Task task) {
1003
        schedule(mongoSession, task.asDocument());
12✔
1004
    }
3✔
1005

1006
    private static void schedule(ClientSession mongoSession, Document taskDoc) {
1007
        log.info("Scheduling task: {}", taskDoc.get("action"));
18✔
1008
        tasksCollection.insertOne(mongoSession, taskDoc);
12✔
1009
    }
3✔
1010

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