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

knowledgepixels / nanopub-registry / 21168631779

20 Jan 2026 10:47AM UTC coverage: 18.824% (+0.06%) from 18.763%
21168631779

push

github

ashleycaselli
test(RegistryDBTest): remove old initLoadingCollections test method

96 of 586 branches covered (16.38%)

Branch coverage included in aggregate %.

352 of 1794 relevant lines covered (19.62%)

3.59 hits per line

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

0.0
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 {
×
35

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

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

47
    },
48

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

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

64
    },
65

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

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

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

88
            setServerStatus(s, coreLoading);
×
89
            schedule(s, INIT_COLLECTIONS);
×
90
        }
×
91

92
    },
93

94
    INIT_COLLECTIONS {
×
95

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

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

105
            IndexInitializer.initLoadingCollections(s);
×
106

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

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

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

132
                );
133

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

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

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

160
    },
161

162
    LOAD_DECLARATIONS {
×
163

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

177
        // DB read from: endorsements, trustEdges, accounts
178
        // DB write to:  endorsements, trustEdges, accounts
179

180
        public void run(ClientSession s, Document taskDoc) {
181

182
            int depth = taskDoc.getInteger("depth");
×
183

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

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

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

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

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

222
                schedule(s, LOAD_DECLARATIONS.with("depth", depth));
×
223

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

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

246
    },
247

248
    EXPAND_TRUST_PATHS {
×
249

250
        // DB read from: accounts, trustPaths, trustEdges
251
        // DB write to:  accounts, trustPaths
252

253
        public void run(ClientSession s, Document taskDoc) {
254

255
            int depth = taskDoc.getInteger("depth");
×
256

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

262
            if (d != null) {
×
263

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

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

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

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

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

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

318
            } else {
×
319

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

322
            }
323

324
        }
×
325

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

342
    },
343

344
    LOAD_CORE {
×
345

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

358
        // DB read from: accounts, trustPaths, endorsements, lists
359
        // DB write to:  accounts, endorsements, lists
360

361
        public void run(ClientSession s, Document taskDoc) {
362

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

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

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

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

414
                set(s, "lists", introList.append("status", loaded.getValue()));
×
415

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

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

453
                set(s, "lists", endorseList.append("status", loaded.getValue()));
×
454

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

459
                set(s, "accounts_loading", agentAccount.append("status", visited.getValue()));
×
460

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

464
        }
×
465

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

481
    },
482

483
    FINISH_ITERATION {
×
484
        public void run(ClientSession s, Document taskDoc) {
485

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

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

500
        }
×
501

502
    },
503

504
    CALCULATE_TRUST_SCORES {
×
505

506
        // DB read from: accounts, trustPaths
507
        // DB write to:  accounts
508

509
        public void run(ClientSession s, Document taskDoc) {
510

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

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

554
        }
×
555

556
    },
557

558
    AGGREGATE_AGENTS {
×
559

560
        // DB read from: accounts, agents
561
        // DB write to:  accounts, agents
562

563
        public void run(ClientSession s, Document taskDoc) {
564

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

590
        }
×
591

592
    },
593

594
    ASSIGN_PUBKEYS {
×
595

596
        // DB read from: accounts
597
        // DB write to:  accounts
598

599
        public void run(ClientSession s, Document taskDoc) {
600

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

617
        }
×
618

619
    },
620

621
    DETERMINE_UPDATES {
×
622

623
        // DB read from: accounts
624
        // DB write to:  accounts
625

626
        public void run(ClientSession s, Document taskDoc) {
627

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

642
        }
×
643

644
    },
645

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

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

657
    },
658

659
    RELEASE_DATA {
×
660
        public void run(ClientSession s, Document taskDoc) {
661
            ServerStatus status = getServerStatus(s);
×
662

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

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

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

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

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

692
    },
693

694
    UPDATE {
×
695
        public void run(ClientSession s, Document taskDoc) {
696

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

706
        }
×
707

708
    },
709

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

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

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

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

752
                schedule(s, LOAD_FULL.withDelay(100));
×
753
            }
754
        }
×
755

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

762
    },
763

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

778
            schedule(s, RUN_OPTIONAL_LOAD.withDelay(100));
×
779
        }
×
780

781
    },
782

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

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

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

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

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

818
                schedule(s, CHECK_NEW.withDelay(100));
×
819
                return;
×
820
            }
821

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

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

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

838
            schedule(s, CHECK_NEW.withDelay(100));
×
839
        }
×
840

841
    },
842

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

849
            schedule(s, LOAD_FULL.withDelay(100));
×
850
        }
×
851

852
    };
853

854
    private static final Logger log = LoggerFactory.getLogger(Task.class);
×
855

856
    public abstract void run(ClientSession s, Document taskDoc) throws Exception;
857

858
    public boolean runAsTransaction() {
859
        return true;
×
860
    }
861

862
    private Document doc() {
863
        return withDelay(0l);
×
864
    }
865

866
    private Document withDelay(long delay) {
867
        return new Document()
×
868
                .append("not-before", System.currentTimeMillis() + delay)
×
869
                .append("action", name());
×
870
    }
871

872
    private Document with(String key, Object value) {
873
        return doc().append(key, value);
×
874
    }
875

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

884
    private static MongoCollection<Document> tasks = collection("tasks");
×
885

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

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

934
    static void runTask(Task task, Document taskDoc) throws Exception {
935
        try (ClientSession s = RegistryDB.getClient().startSession()) {
×
936
            task.run(s, taskDoc);
×
937
            tasks.deleteOne(s, eq("_id", taskDoc.get("_id")));
×
938
        }
939
    }
×
940

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

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

979
    private static IntroNanopub getAgentIntro(ClientSession mongoSession, String nanopubId) {
980
        IntroNanopub agentIntro = new IntroNanopub(NanopubLoader.retrieveNanopub(mongoSession, nanopubId));
×
981
        if (agentIntro.getUser() == null) return null;
×
982
        loadNanopub(mongoSession, agentIntro.getNanopub());
×
983
        return agentIntro;
×
984
    }
985

986
    private static void setServerStatus(ClientSession mongoSession, ServerStatus status) {
987
        setValue(mongoSession, Collection.SERVER_INFO.toString(), "status", status.toString());
×
988
    }
×
989

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

998
    private static void schedule(ClientSession mongoSession, Task task) {
999
        schedule(mongoSession, task.doc());
×
1000
    }
×
1001

1002
    private static void schedule(ClientSession mongoSession, Document taskDoc) {
1003
        log.info("Scheduling task: {}", taskDoc.get("action"));
×
1004
        tasks.insertOne(mongoSession, taskDoc);
×
1005
    }
×
1006

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