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

knowledgepixels / nanopub-registry / 24498287812

16 Apr 2026 07:41AM UTC coverage: 31.57% (-0.6%) from 32.151%
24498287812

push

github

web-flow
Merge pull request #108 from knowledgepixels/feature/107-trust-state-snapshots

feat: hash-keyed trust state snapshots (#107)

277 of 984 branches covered (28.15%)

Branch coverage included in aggregate %.

827 of 2513 relevant lines covered (32.91%)

5.47 hits per line

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

11.89
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 com.mongodb.client.model.ReplaceOptions;
9
import net.trustyuri.TrustyUriUtils;
10
import org.apache.commons.lang.Validate;
11
import org.bson.Document;
12
import org.eclipse.rdf4j.model.IRI;
13
import org.eclipse.rdf4j.model.Statement;
14
import org.nanopub.Nanopub;
15
import org.nanopub.extra.index.IndexUtils;
16
import org.nanopub.extra.index.NanopubIndex;
17
import org.nanopub.extra.security.KeyDeclaration;
18
import org.nanopub.extra.setting.IntroNanopub;
19
import org.nanopub.extra.setting.NanopubSetting;
20
import org.slf4j.Logger;
21
import org.slf4j.LoggerFactory;
22

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

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

35
public enum Task implements Serializable {
6✔
36

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

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

50
    },
51

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

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

67
    },
68

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

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

87
            if (!"false".equals(System.getenv("REGISTRY_PERFORM_FULL_LOAD"))) {
15!
88
                long fullLoadDelay = "false".equals(System.getenv("REGISTRY_ENABLE_TRUST_CALCULATION")) ? 0 : 60 * 1000;
21!
89
                schedule(s, LOAD_FULL.withDelay(fullLoadDelay));
15✔
90
            }
91

92
            setServerStatus(s, coreLoading);
9✔
93
            schedule(s, INIT_COLLECTIONS);
9✔
94
        }
3✔
95

96
    },
97

98
    INIT_COLLECTIONS {
33✔
99

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

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

109
            IndexInitializer.initLoadingCollections(s);
×
110

111
            if ("false".equals(System.getenv("REGISTRY_ENABLE_TRUST_CALCULATION"))) {
×
112
                log.info("Trust calculation disabled; skipping to FINALIZE_TRUST_STATE");
×
113
                for (Map.Entry<String, Integer> entry : AgentFilter.getExplicitPubkeys().entrySet()) {
×
114
                    String pubkeyHash = entry.getKey();
×
115
                    int quota = entry.getValue();
×
116
                    Document account = new Document("agent", "")
×
117
                            .append("pubkey", pubkeyHash)
×
118
                            .append("status", toLoad.getValue())
×
119
                            .append("depth", 0)
×
120
                            .append("quota", quota);
×
121
                    if (!has(s, "accounts_loading", new Document("pubkey", pubkeyHash))) {
×
122
                        insert(s, "accounts_loading", account);
×
123
                        log.info("Seeded explicit pubkey as account: {}", pubkeyHash);
×
124
                    }
125
                }
×
126
                schedule(s, FINALIZE_TRUST_STATE);
×
127
                return;
×
128
            }
129

130
            // since this may take long, we start with postfix "_loading"
131
            // and only at completion it's changed to trustPath, endorsements, accounts
132
            insert(s, "trustPaths_loading",
×
133
                    new Document("_id", "$")
134
                            .append("sorthash", "")
×
135
                            .append("agent", "$")
×
136
                            .append("pubkey", "$")
×
137
                            .append("depth", 0)
×
138
                            .append("ratio", 1.0d)
×
139
                            .append("type", "extended")
×
140
            );
141

142
            NanopubIndex agentIndex = IndexUtils.castToIndex(NanopubLoader.retrieveNanopub(s, Utils.getSetting().getAgentIntroCollection().stringValue()));
×
143
            loadNanopub(s, agentIndex);
×
144
            for (IRI el : agentIndex.getElements()) {
×
145
                String declarationAc = TrustyUriUtils.getArtifactCode(el.stringValue());
×
146
                Validate.notNull(declarationAc);
×
147

148
                insert(s, "endorsements_loading",
×
149
                        new Document("agent", "$")
150
                                .append("pubkey", "$")
×
151
                                .append("endorsedNanopub", declarationAc)
×
152
                                .append("source", getValue(s, Collection.SETTING.toString(), "current").toString())
×
153
                                .append("status", toRetrieve.getValue())
×
154

155
                );
156

157
            }
×
158
            insert(s, "accounts_loading",
×
159
                    new Document("agent", "$")
160
                            .append("pubkey", "$")
×
161
                            .append("status", visited.getValue())
×
162
                            .append("depth", 0)
×
163
            );
164

165
            log.info("Starting iteration at depth 0");
×
166
            schedule(s, LOAD_DECLARATIONS.with("depth", 1));
×
167
        }
×
168

169
        // At the end of this task, the base agent is initialized:
170
        // ------------------------------------------------------------
171
        //
172
        //              $$$$ ----endorses----> [intro]
173
        //              base                (to-retrieve)
174
        //              $$$$
175
        //            (visited)
176
        //
177
        //              [0] trust path
178
        //
179
        // ------------------------------------------------------------
180
        // Only one endorses-link to an introduction is shown here,
181
        // but there are typically several.
182

183
    },
184

185
    LOAD_DECLARATIONS {
33✔
186

187
        // In general, we have at this point accounts with
188
        // endorsement links to unvisited agent introductions:
189
        // ------------------------------------------------------------
190
        //
191
        //         o      ----endorses----> [intro]
192
        //    --> /#\  /o\___            (to-retrieve)
193
        //        / \  \_/^^^
194
        //         (visited)
195
        //
196
        //    ========[X] trust path
197
        //
198
        // ------------------------------------------------------------
199

200
        // DB read from: endorsements, trustEdges, accounts
201
        // DB write to:  endorsements, trustEdges, accounts
202

203
        public void run(ClientSession s, Document taskDoc) {
204

205
            int depth = taskDoc.getInteger("depth");
×
206

207
            if (has(s, "endorsements_loading", new Document("status", toRetrieve.getValue()))) {
×
208
                Document d = getOne(s, "endorsements_loading",
×
209
                        new DbEntryWrapper(toRetrieve).getDocument());
×
210

211
                IntroNanopub agentIntro = getAgentIntro(s, d.getString("endorsedNanopub"));
×
212
                if (agentIntro != null) {
×
213
                    String agentId = agentIntro.getUser().stringValue();
×
214

215
                    for (KeyDeclaration kd : agentIntro.getKeyDeclarations()) {
×
216
                        String sourceAgent = d.getString("agent");
×
217
                        Validate.notNull(sourceAgent);
×
218
                        String sourcePubkey = d.getString("pubkey");
×
219
                        Validate.notNull(sourcePubkey);
×
220
                        String sourceAc = d.getString("source");
×
221
                        Validate.notNull(sourceAc);
×
222
                        String agentPubkey = Utils.getHash(kd.getPublicKeyString());
×
223
                        Validate.notNull(agentPubkey);
×
224
                        Document trustEdge = new Document("fromAgent", sourceAgent)
×
225
                                .append("fromPubkey", sourcePubkey)
×
226
                                .append("toAgent", agentId)
×
227
                                .append("toPubkey", agentPubkey)
×
228
                                .append("source", sourceAc);
×
229
                        if (!has(s, "trustEdges", trustEdge)) {
×
230
                            boolean invalidated = has(s, "invalidations", new Document("invalidatedNp", sourceAc).append("invalidatingPubkey", sourcePubkey));
×
231
                            insert(s, "trustEdges", trustEdge.append("invalidated", invalidated));
×
232
                        }
233

234
                        Document agent = new Document("agent", agentId).append("pubkey", agentPubkey);
×
235
                        if (!has(s, "accounts_loading", agent)) {
×
236
                            insert(s, "accounts_loading", agent.append("status", seen.getValue()).append("depth", depth));
×
237
                        }
238
                    }
×
239

240
                    set(s, "endorsements_loading", d.append("status", retrieved.getValue()));
×
241
                } else {
×
242
                    set(s, "endorsements_loading", d.append("status", discarded.getValue()));
×
243
                }
244

245
                schedule(s, LOAD_DECLARATIONS.with("depth", depth));
×
246

247
            } else {
×
248
                schedule(s, EXPAND_TRUST_PATHS.with("depth", depth));
×
249
            }
250
        }
×
251

252
        // At the end of this step, the key declarations in the agent
253
        // introductions are loaded and the corresponding trust edges
254
        // established:
255
        // ------------------------------------------------------------
256
        //
257
        //        o      ----endorses----> [intro]
258
        //   --> /#\  /o\___                o
259
        //       / \  \_/^^^ ---trusts---> /#\  /o\___
260
        //        (visited)                / \  \_/^^^
261
        //                                   (seen)
262
        //
263
        //   ========[X] trust path
264
        //
265
        // ------------------------------------------------------------
266
        // Only one trust edge per introduction is shown here, but
267
        // there can be several.
268

269
    },
270

271
    EXPAND_TRUST_PATHS {
33✔
272

273
        // DB read from: accounts, trustPaths, trustEdges
274
        // DB write to:  accounts, trustPaths
275

276
        public void run(ClientSession s, Document taskDoc) {
277

278
            int depth = taskDoc.getInteger("depth");
×
279

280
            Document d = getOne(s, "accounts_loading",
×
281
                    new Document("status", visited.getValue())
×
282
                            .append("depth", depth - 1)
×
283
            );
284

285
            if (d != null) {
×
286

287
                String agentId = d.getString("agent");
×
288
                Validate.notNull(agentId);
×
289
                String pubkeyHash = d.getString("pubkey");
×
290
                Validate.notNull(pubkeyHash);
×
291

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

296
                if (trustPath == null) {
×
297
                    // Check it again in next iteration:
298
                    set(s, "accounts_loading", d.append("depth", depth));
×
299
                } else {
300
                    // Only first matching trust path is considered
301

302
                    Map<String, Document> newPaths = new HashMap<>();
×
303
                    Map<String, Set<String>> pubkeySets = new HashMap<>();
×
304
                    String currentSetting = getValue(s, Collection.SETTING.toString(), "current").toString();
×
305

306
                    MongoCursor<Document> edgeCursor = get(s, "trustEdges",
×
307
                            new Document("fromAgent", agentId)
308
                                    .append("fromPubkey", pubkeyHash)
×
309
                                    .append("invalidated", false)
×
310
                    );
311
                    while (edgeCursor.hasNext()) {
×
312
                        Document e = edgeCursor.next();
×
313

314
                        String agent = e.getString("toAgent");
×
315
                        Validate.notNull(agent);
×
316
                        String pubkey = e.getString("toPubkey");
×
317
                        Validate.notNull(pubkey);
×
318
                        String pathId = trustPath.getString("_id") + " " + agent + "|" + pubkey;
×
319
                        newPaths.put(pathId,
×
320
                                new Document("_id", pathId)
321
                                        .append("sorthash", Utils.getHash(currentSetting + " " + pathId))
×
322
                                        .append("agent", agent)
×
323
                                        .append("pubkey", pubkey)
×
324
                                        .append("depth", depth)
×
325
                                        .append("type", "extended")
×
326
                        );
327
                        if (!pubkeySets.containsKey(agent)) pubkeySets.put(agent, new HashSet<>());
×
328
                        pubkeySets.get(agent).add(pubkey);
×
329
                    }
×
330
                    for (String pathId : newPaths.keySet()) {
×
331
                        Document pd = newPaths.get(pathId);
×
332
                        // first divide by agents; then for each agent, divide by number of pubkeys:
333
                        double newRatio = (trustPath.getDouble("ratio") * 0.9) / pubkeySets.size() / pubkeySets.get(pd.getString("agent")).size();
×
334
                        insert(s, "trustPaths_loading", pd.append("ratio", newRatio));
×
335
                    }
×
336
                    // Retain only 10% of the ratio — the other 90% was distributed to children
337
                    double retainedRatio = trustPath.getDouble("ratio") * 0.1;
×
338
                    set(s, "trustPaths_loading", trustPath.append("type", "primary").append("ratio", retainedRatio));
×
339
                    set(s, "accounts_loading", d.append("status", expanded.getValue()));
×
340
                }
341
                schedule(s, EXPAND_TRUST_PATHS.with("depth", depth));
×
342

343
            } else {
×
344

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

347
            }
348

349
        }
×
350

351
        // At the end of this step, trust paths are updated to include
352
        // the new accounts:
353
        // ------------------------------------------------------------
354
        //
355
        //         o      ----endorses----> [intro]
356
        //    --> /#\  /o\___                o
357
        //        / \  \_/^^^ ---trusts---> /#\  /o\___
358
        //        (expanded)                / \  \_/^^^
359
        //                                    (seen)
360
        //
361
        //    ========[X]=====================[X+1] trust path
362
        //
363
        // ------------------------------------------------------------
364
        // Only one trust path is shown here, but they branch out if
365
        // several trust edges are present.
366

367
    },
368

369
    LOAD_CORE {
33✔
370

371
        // From here on, we refocus on the head of the trust paths:
372
        // ------------------------------------------------------------
373
        //
374
        //         o
375
        //    --> /#\  /o\___
376
        //        / \  \_/^^^
377
        //          (seen)
378
        //
379
        //    ========[X] trust path
380
        //
381
        // ------------------------------------------------------------
382

383
        // DB read from: accounts, trustPaths, endorsements, lists
384
        // DB write to:  accounts, endorsements, lists
385

386
        public void run(ClientSession s, Document taskDoc) {
387

388
            int depth = taskDoc.getInteger("depth");
×
389
            int loadCount = taskDoc.getInteger("load-count");
×
390

391
            Document agentAccount = getOne(s, "accounts_loading",
×
392
                    new Document("depth", depth).append("status", seen.getValue()));
×
393
            final String agentId;
394
            final String pubkeyHash;
395
            final Document trustPath;
396
            if (agentAccount != null) {
×
397
                agentId = agentAccount.getString("agent");
×
398
                Validate.notNull(agentId);
×
399
                pubkeyHash = agentAccount.getString("pubkey");
×
400
                Validate.notNull(pubkeyHash);
×
401
                trustPath = getOne(s, "trustPaths_loading",
×
402
                        new Document("depth", depth)
×
403
                                .append("agent", agentId)
×
404
                                .append("pubkey", pubkeyHash)
×
405
                );
406
            } else {
407
                agentId = null;
×
408
                pubkeyHash = null;
×
409
                trustPath = null;
×
410
            }
411

412
            if (agentAccount == null) {
×
413
                schedule(s, FINISH_ITERATION.with("depth", depth).append("load-count", loadCount));
×
414
            } else if (trustPath == null) {
×
415
                // Account was seen but has no trust path at this depth; skip it
416
                set(s, "accounts_loading", agentAccount.append("status", skipped.getValue()));
×
417
                schedule(s, LOAD_CORE.with("depth", depth).append("load-count", loadCount));
×
418
            } else if (trustPath.getDouble("ratio") < MIN_TRUST_PATH_RATIO) {
×
419
                set(s, "accounts_loading", agentAccount.append("status", skipped.getValue()));
×
420
                Document d = new Document("pubkey", pubkeyHash).append("type", INTRO_TYPE_HASH);
×
421
                if (!has(s, "lists", d)) {
×
422
                    insert(s, "lists", d.append("status", encountered.getValue()));
×
423
                }
424
                schedule(s, LOAD_CORE.with("depth", depth).append("load-count", loadCount + 1));
×
425
            } else {
×
426
                // TODO check intro limit
427
                Document introList = new Document()
×
428
                        .append("pubkey", pubkeyHash)
×
429
                        .append("type", INTRO_TYPE_HASH)
×
430
                        .append("status", loading.getValue());
×
431
                if (!has(s, "lists", new Document("pubkey", pubkeyHash).append("type", INTRO_TYPE_HASH))) {
×
432
                    insert(s, "lists", introList);
×
433
                }
434

435
                // No checksum skip in LOAD_CORE: the endorsement extraction logic (below) needs to
436
                // see every nanopub to populate endorsements_loading, which is rebuilt from scratch each UPDATE.
437
                try (var stream = NanopubLoader.retrieveNanopubsFromPeers(INTRO_TYPE_HASH, pubkeyHash)) {
×
438
                    NanopubLoader.loadStreamInParallel(stream, np -> {
×
439
                        try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
440
                            loadNanopub(ws, np, pubkeyHash, INTRO_TYPE);
×
441
                        }
442
                    });
×
443
                }
444

445
                set(s, "lists", introList.append("status", loaded.getValue()));
×
446

447
                // TODO check endorsement limit
448
                Document endorseList = new Document()
×
449
                        .append("pubkey", pubkeyHash)
×
450
                        .append("type", ENDORSE_TYPE_HASH)
×
451
                        .append("status", loading.getValue());
×
452
                if (!has(s, "lists", new Document("pubkey", pubkeyHash).append("type", ENDORSE_TYPE_HASH))) {
×
453
                    insert(s, "lists", endorseList);
×
454
                }
455

456
                try (var stream = NanopubLoader.retrieveNanopubsFromPeers(ENDORSE_TYPE_HASH, pubkeyHash)) {
×
457
                    stream.forEach(m -> {
×
458
                        if (!m.isSuccess())
×
459
                            throw new AbortingTaskException("Failed to download nanopub; aborting task...");
×
460
                        Nanopub nanopub = m.getNanopub();
×
461
                        loadNanopub(s, nanopub, pubkeyHash, ENDORSE_TYPE);
×
462
                        String sourceNpId = TrustyUriUtils.getArtifactCode(nanopub.getUri().stringValue());
×
463
                        Validate.notNull(sourceNpId);
×
464
                        for (Statement st : nanopub.getAssertion()) {
×
465
                            if (!st.getPredicate().equals(Utils.APPROVES_OF)) continue;
×
466
                            if (!(st.getObject() instanceof IRI)) continue;
×
467
                            if (!agentId.equals(st.getSubject().stringValue())) continue;
×
468
                            String objStr = st.getObject().stringValue();
×
469
                            if (!TrustyUriUtils.isPotentialTrustyUri(objStr)) continue;
×
470
                            String endorsedNpId = TrustyUriUtils.getArtifactCode(objStr);
×
471
                            Validate.notNull(endorsedNpId);
×
472
                            Document endorsement = new Document("agent", agentId)
×
473
                                    .append("pubkey", pubkeyHash)
×
474
                                    .append("endorsedNanopub", endorsedNpId)
×
475
                                    .append("source", sourceNpId);
×
476
                            if (!has(s, "endorsements_loading", endorsement)) {
×
477
                                insert(s, "endorsements_loading",
×
478
                                        endorsement.append("status", toRetrieve.getValue()));
×
479
                            }
480
                        }
×
481
                    });
×
482
                }
483

484
                set(s, "lists", endorseList.append("status", loaded.getValue()));
×
485

486
                Document df = new Document("pubkey", pubkeyHash).append("type", "$");
×
487
                if (!has(s, "lists", df)) insert(s, "lists",
×
488
                        df.append("status", encountered.getValue()));
×
489

490
                set(s, "accounts_loading", agentAccount.append("status", visited.getValue()));
×
491

492
                schedule(s, LOAD_CORE.with("depth", depth).append("load-count", loadCount + 1));
×
493
            }
494

495
        }
×
496

497
        // At the end of this step, we have added new endorsement
498
        // links to yet-to-retrieve agent introductions:
499
        // ------------------------------------------------------------
500
        //
501
        //         o      ----endorses----> [intro]
502
        //    --> /#\  /o\___            (to-retrieve)
503
        //        / \  \_/^^^
504
        //         (visited)
505
        //
506
        //    ========[X] trust path
507
        //
508
        // ------------------------------------------------------------
509
        // Only one endorsement is shown here, but there are typically
510
        // several.
511

512
    },
513

514
    FINISH_ITERATION {
33✔
515
        public void run(ClientSession s, Document taskDoc) {
516

517
            int depth = taskDoc.getInteger("depth");
×
518
            int loadCount = taskDoc.getInteger("load-count");
×
519

520
            if (loadCount == 0) {
×
521
                log.info("No new cores loaded; finishing iteration");
×
522
                schedule(s, CALCULATE_TRUST_SCORES);
×
523
            } else if (depth == MAX_TRUST_PATH_DEPTH) {
×
524
                log.info("Maximum depth reached: {}", depth);
×
525
                schedule(s, CALCULATE_TRUST_SCORES);
×
526
            } else {
527
                log.info("Progressing iteration at depth {}", depth + 1);
×
528
                schedule(s, LOAD_DECLARATIONS.with("depth", depth + 1));
×
529
            }
530

531
        }
×
532

533
    },
534

535
    CALCULATE_TRUST_SCORES {
33✔
536

537
        // DB read from: accounts, trustPaths
538
        // DB write to:  accounts
539

540
        public void run(ClientSession s, Document taskDoc) {
541

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

544
            if (d == null) {
×
545
                schedule(s, AGGREGATE_AGENTS);
×
546
            } else {
547
                double ratio = 0.0;
×
548
                Map<String, Boolean> seenPathElements = new HashMap<>();
×
549
                int pathCount = 0;
×
550
                MongoCursor<Document> trustPaths = collection("trustPaths_loading").find(s,
×
551
                        new Document("agent", d.get("agent").toString()).append("pubkey", d.get("pubkey").toString())
×
552
                ).sort(orderBy(ascending("depth"), descending("ratio"), ascending("sorthash"))).cursor();
×
553
                while (trustPaths.hasNext()) {
×
554
                    Document trustPath = trustPaths.next();
×
555
                    ratio += trustPath.getDouble("ratio");
×
556
                    boolean independentPath = true;
×
557
                    String[] pathElements = trustPath.getString("_id").split(" ");
×
558
                    // Iterate over path elements, ignoring first (root) and last (this agent/pubkey):
559
                    for (int i = 1; i < pathElements.length - 1; i++) {
×
560
                        String p = pathElements[i];
×
561
                        if (seenPathElements.containsKey(p)) {
×
562
                            independentPath = false;
×
563
                            break;
×
564
                        }
565
                        seenPathElements.put(p, true);
×
566
                    }
567
                    if (independentPath) pathCount += 1;
×
568
                }
×
569
                double rawQuota = GLOBAL_QUOTA * ratio;
×
570
                int quota = (int) rawQuota;
×
571
                if (rawQuota < MIN_USER_QUOTA) {
×
572
                    quota = MIN_USER_QUOTA;
×
573
                } else if (rawQuota > MAX_USER_QUOTA) {
×
574
                    quota = MAX_USER_QUOTA;
×
575
                }
576
                set(s, "accounts_loading",
×
577
                        d.append("status", processed.getValue())
×
578
                                .append("ratio", ratio)
×
579
                                .append("pathCount", pathCount)
×
580
                                .append("quota", quota)
×
581
                );
582
                schedule(s, CALCULATE_TRUST_SCORES);
×
583
            }
584

585
        }
×
586

587
    },
588

589
    AGGREGATE_AGENTS {
33✔
590

591
        // DB read from: accounts, agents
592
        // DB write to:  accounts, agents
593

594
        public void run(ClientSession s, Document taskDoc) {
595

596
            Document a = getOne(s, "accounts_loading", new Document("status", processed.getValue()));
×
597
            if (a == null) {
×
598
                schedule(s, ASSIGN_PUBKEYS);
×
599
            } else {
600
                Document agentId = new Document("agent", a.get("agent").toString()).append("status", processed.getValue());
×
601
                int count = 0;
×
602
                int pathCountSum = 0;
×
603
                double totalRatio = 0.0d;
×
604
                MongoCursor<Document> agentAccounts = collection("accounts_loading").find(s, agentId).cursor();
×
605
                while (agentAccounts.hasNext()) {
×
606
                    Document d = agentAccounts.next();
×
607
                    count++;
×
608
                    pathCountSum += d.getInteger("pathCount");
×
609
                    totalRatio += d.getDouble("ratio");
×
610
                }
×
611
                collection("accounts_loading").updateMany(s, agentId, new Document("$set",
×
612
                        new DbEntryWrapper(aggregated).getDocument()));
×
613
                insert(s, "agents_loading",
×
614
                        agentId.append("accountCount", count)
×
615
                                .append("avgPathCount", (double) pathCountSum / count)
×
616
                                .append("totalRatio", totalRatio)
×
617
                );
618
                schedule(s, AGGREGATE_AGENTS);
×
619
            }
620

621
        }
×
622

623
    },
624

625
    ASSIGN_PUBKEYS {
33✔
626

627
        // DB read from: accounts
628
        // DB write to:  accounts
629

630
        public void run(ClientSession s, Document taskDoc) {
631

632
            Document a = getOne(s, "accounts_loading", new DbEntryWrapper(aggregated).getDocument());
×
633
            if (a == null) {
×
634
                schedule(s, DETERMINE_UPDATES);
×
635
            } else {
636
                Document pubkeyId = new Document("pubkey", a.get("pubkey").toString());
×
637
                if (collection("accounts_loading").countDocuments(s, pubkeyId) == 1) {
×
638
                    collection("accounts_loading").updateMany(s, pubkeyId,
×
639
                            new Document("$set", new DbEntryWrapper(approved).getDocument()));
×
640
                } else {
641
                    // TODO At the moment all get marked as 'contested'; implement more nuanced algorithm
642
                    collection("accounts_loading").updateMany(s, pubkeyId, new Document("$set",
×
643
                            new DbEntryWrapper(contested).getDocument()));
×
644
                }
645
                schedule(s, ASSIGN_PUBKEYS);
×
646
            }
647

648
        }
×
649

650
    },
651

652
    DETERMINE_UPDATES {
33✔
653

654
        // DB read from: accounts
655
        // DB write to:  accounts
656

657
        public void run(ClientSession s, Document taskDoc) {
658

659
            // TODO Handle contested accounts properly:
660
            for (Document d : collection("accounts_loading").find(
×
661
                    new DbEntryWrapper(approved).getDocument())) {
×
662
                // TODO Consider quota too:
663
                Document accountId = new Document("agent", d.get("agent").toString()).append("pubkey", d.get("pubkey").toString());
×
664
                if (collection(Collection.ACCOUNTS.toString()) == null || !has(s, Collection.ACCOUNTS.toString(),
×
665
                        accountId.append("status", loaded.getValue()))) {
×
666
                    set(s, "accounts_loading", d.append("status", toLoad.getValue()));
×
667
                } else {
668
                    set(s, "accounts_loading", d.append("status", loaded.getValue()));
×
669
                }
670
            }
×
671
            schedule(s, FINALIZE_TRUST_STATE);
×
672

673
        }
×
674

675
    },
676

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

685
            schedule(s, RELEASE_DATA.with("newTrustStateHash", newTrustStateHash).append("previousTrustStateHash", previousTrustStateHash));
×
686
        }
×
687

688
    },
689

690
    RELEASE_DATA {
33✔
691

692
        private static final int TRUST_STATE_SNAPSHOT_RETENTION = 100;
693

694
        public void run(ClientSession s, Document taskDoc) {
695
            ServerStatus status = getServerStatus(s);
×
696

697
            String newTrustStateHash = taskDoc.get("newTrustStateHash").toString();
×
698
            String previousTrustStateHash = taskDoc.getString("previousTrustStateHash");  // may be null
×
699

700
            // Renaming collections is run outside of a transaction, but is idempotent operation, so can safely be retried if task fails:
701
            rename("accounts_loading", Collection.ACCOUNTS.toString());
×
702
            rename("trustPaths_loading", "trustPaths");
×
703
            rename("agents_loading", Collection.AGENTS.toString());
×
704
            rename("endorsements_loading", "endorsements");
×
705

706
            if (previousTrustStateHash == null || !previousTrustStateHash.equals(newTrustStateHash)) {
×
707
                increaseStateCounter(s);
×
708
                setValue(s, Collection.SERVER_INFO.toString(), "trustStateHash", newTrustStateHash);
×
709
                Object trustStateCounter = getValue(s, Collection.SERVER_INFO.toString(), "trustStateCounter");
×
710
                insert(s, "debug_trustPaths", new Document()
×
711
                        .append("trustStateTxt", DebugPage.getTrustPathsTxt(s))
×
712
                        .append("trustStateHash", newTrustStateHash)
×
713
                        .append("trustStateCounter", trustStateCounter)
×
714
                );
715

716
                // Structured hash-keyed snapshot for consumer mirroring (#107).
717
                // Reads the accounts collection just renamed from accounts_loading above (:697).
718
                List<Document> snapshotAccounts = new ArrayList<>();
×
719
                for (Document a : collection(Collection.ACCOUNTS.toString()).find(s)) {
×
720
                    String pubkey = a.getString("pubkey");
×
721
                    if ("$".equals(pubkey)) continue;
×
722
                    snapshotAccounts.add(new Document()
×
723
                            .append("pubkey", pubkey)
×
724
                            .append("agent", a.getString("agent"))
×
725
                            .append("status", a.getString("status"))
×
726
                            .append("depth", a.get("depth"))
×
727
                            .append("pathCount", a.get("pathCount"))
×
728
                            .append("ratio", a.get("ratio"))
×
729
                            .append("quota", a.get("quota")));
×
730
                }
×
731
                Document snapshot = new Document()
×
732
                        .append("_id", newTrustStateHash)
×
733
                        .append("trustStateCounter", trustStateCounter)
×
734
                        .append("createdAt", ZonedDateTime.now().toString())
×
735
                        .append("accounts", snapshotAccounts);
×
736
                collection(Collection.TRUST_STATE_SNAPSHOTS.toString()).replaceOne(
×
737
                        s,
738
                        new Document("_id", newTrustStateHash),
739
                        snapshot,
740
                        new ReplaceOptions().upsert(true));
×
741

742
                // Prune beyond retention: collect _ids of snapshots past the Nth most recent, delete them.
743
                // trustStateCounter is monotonically increasing (see increaseStateCounter above), so ordering is well-defined.
744
                List<Object> toPrune = new ArrayList<>();
×
745
                try (MongoCursor<Document> stale = collection(Collection.TRUST_STATE_SNAPSHOTS.toString())
×
746
                        .find(s)
×
747
                        .sort(descending("trustStateCounter"))
×
748
                        .skip(TRUST_STATE_SNAPSHOT_RETENTION)
×
749
                        .projection(new Document("_id", 1))
×
750
                        .cursor()) {
×
751
                    while (stale.hasNext()) {
×
752
                        toPrune.add(stale.next().get("_id"));
×
753
                    }
754
                }
755
                if (!toPrune.isEmpty()) {
×
756
                    collection(Collection.TRUST_STATE_SNAPSHOTS.toString()).deleteMany(
×
757
                            s, new Document("_id", new Document("$in", toPrune)));
758
                }
759
            }
760

761
            if (status == coreLoading) {
×
762
                setServerStatus(s, coreReady);
×
763
            } else {
764
                setServerStatus(s, ready);
×
765
            }
766

767
            // Run update after 1h:
768
            schedule(s, UPDATE.withDelay(60 * 60 * 1000));
×
769
        }
×
770

771
    },
772

773
    UPDATE {
33✔
774
        public void run(ClientSession s, Document taskDoc) {
775
            ServerStatus status = getServerStatus(s);
×
776
            if (status == ready || status == coreReady) {
×
777
                setServerStatus(s, updating);
×
778
                schedule(s, INIT_COLLECTIONS);
×
779
            } else {
780
                log.info("Postponing update; currently in status {}", status);
×
781
                schedule(s, UPDATE.withDelay(10 * 60 * 1000));
×
782
            }
783

784
        }
×
785

786
    },
787

788
    LOAD_FULL {
33✔
789
        public void run(ClientSession s, Document taskDoc) {
790
            if ("false".equals(System.getenv("REGISTRY_PERFORM_FULL_LOAD"))) return;
15!
791

792
            ServerStatus status = getServerStatus(s);
9✔
793
            if (status != coreReady && status != ready && status != updating) {
27!
794
                long retryDelay = "false".equals(System.getenv("REGISTRY_ENABLE_TRUST_CALCULATION")) ? 100 : 60 * 1000;
21!
795
                log.info("Server currently not ready; checking again later");
9✔
796
                schedule(s, LOAD_FULL.withDelay(retryDelay));
15✔
797
                return;
3✔
798
            }
799

800
            Document a = getOne(s, Collection.ACCOUNTS.toString(), new DbEntryWrapper(toLoad).getDocument());
×
801
            if (a == null) {
×
802
                log.info("Nothing to load");
×
803
                if (status == coreReady) {
×
804
                    log.info("Full load finished");
×
805
                    setServerStatus(s, ready);
×
806
                }
807
                log.info("Scheduling optional loading checks");
×
808
                schedule(s, RUN_OPTIONAL_LOAD.withDelay(100));
×
809
            } else {
810
                final String ph = a.getString("pubkey");
×
811
                boolean quotaReached = false;
×
812
                if (!ph.equals("$")) {
×
813
                    if (!AgentFilter.isAllowed(s, ph)) {
×
814
                        log.info("Skipping pubkey {} (not covered by agent filter)", ph);
×
815
                        set(s, Collection.ACCOUNTS.toString(), a.append("status", skipped.getValue()));
×
816
                        schedule(s, LOAD_FULL.withDelay(100));
×
817
                        return;
×
818
                    }
819
                    if (AgentFilter.isOverQuota(s, ph)) {
×
820
                        log.info("Skipping pubkey {} (quota exceeded)", ph);
×
821
                        quotaReached = true;
×
822
                    } else {
823
                        long startTime = System.nanoTime();
×
824
                        AtomicLong totalLoaded = new AtomicLong(0);
×
825

826
                        // Load per covered type (or "$" if no restriction) with checksum skip-ahead
827
                        for (String typeHash : getLoadTypeHashes(s, ph)) {
×
828
                            String checksums = buildChecksumFallbacks(s, ph, typeHash);
×
829
                            try (var stream = NanopubLoader.retrieveNanopubsFromPeers(typeHash, ph, checksums)) {
×
830
                                NanopubLoader.loadStreamInParallel(stream, np -> {
×
831
                                    if (!CoverageFilter.isCovered(np)) return;
×
832
                                    try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
833
                                        if (!AgentFilter.isOverQuota(ws, ph)) {
×
834
                                            loadNanopub(ws, np, ph, "$");
×
835
                                            totalLoaded.incrementAndGet();
×
836
                                        }
837
                                    }
838
                                });
×
839
                            }
840
                        }
×
841

842
                        double timeSeconds = (System.nanoTime() - startTime) * 1e-9;
×
843
                        log.info("Loaded {} nanopubs in {}s, {} np/s",
×
844
                                totalLoaded.get(), timeSeconds, String.format("%.2f", totalLoaded.get() / timeSeconds));
×
845

846
                        if (AgentFilter.isOverQuota(s, ph)) {
×
847
                            quotaReached = true;
×
848
                        }
849
                    }
850
                }
851

852
                Document l = getOne(s, "lists", new Document().append("pubkey", ph).append("type", "$"));
×
853
                if (l != null) set(s, "lists", l.append("status", loaded.getValue()));
×
854
                EntryStatus accountStatus = quotaReached ? capped : loaded;
×
855
                int effectiveQuota = AgentFilter.getQuota(s, ph);
×
856
                if (effectiveQuota >= 0) {
×
857
                    a.append("quota", effectiveQuota);
×
858
                }
859
                set(s, Collection.ACCOUNTS.toString(), a.append("status", accountStatus.getValue()));
×
860

861
                schedule(s, LOAD_FULL.withDelay(100));
×
862
            }
863
        }
×
864

865
        @Override
866
        public boolean runAsTransaction() {
867
            // TODO Make this a transaction once we connect to other Nanopub Registry instances:
868
            return false;
×
869
        }
870

871
    },
872

873
    RUN_OPTIONAL_LOAD {
33✔
874

875
        private static final int BATCH_SIZE = Integer.parseInt(
15✔
876
                Utils.getEnv("REGISTRY_OPTIONAL_LOAD_BATCH_SIZE", "100"));
3✔
877

878
        public void run(ClientSession s, Document taskDoc) {
879
            if ("false".equals(System.getenv("REGISTRY_ENABLE_OPTIONAL_LOAD"))) {
×
880
                schedule(s, CHECK_NEW.withDelay(500));
×
881
                return;
×
882
            }
883

884
            AtomicLong totalLoaded = new AtomicLong(0);
×
885

886
            // Phase 1: Process encountered intro lists (core loading)
887
            while (totalLoaded.get() < BATCH_SIZE) {
×
888
                Document di = getOne(s, "lists", new Document("type", INTRO_TYPE_HASH).append("status", encountered.getValue()));
×
889
                if (di == null) break;
×
890

891
                final String pubkeyHash = di.getString("pubkey");
×
892
                Validate.notNull(pubkeyHash);
×
893
                log.info("Optional core loading: {}", pubkeyHash);
×
894

895
                String introChecksums = buildChecksumFallbacks(s, pubkeyHash, INTRO_TYPE_HASH);
×
896
                try (var stream = NanopubLoader.retrieveNanopubsFromPeers(INTRO_TYPE_HASH, pubkeyHash, introChecksums)) {
×
897
                    NanopubLoader.loadStreamInParallel(stream, np -> {
×
898
                        try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
899
                            loadNanopub(ws, np, pubkeyHash, INTRO_TYPE);
×
900
                            totalLoaded.incrementAndGet();
×
901
                        }
902
                    });
×
903
                }
904
                set(s, "lists", di.append("status", loaded.getValue()));
×
905

906
                String endorseChecksums = buildChecksumFallbacks(s, pubkeyHash, ENDORSE_TYPE_HASH);
×
907
                try (var stream = NanopubLoader.retrieveNanopubsFromPeers(ENDORSE_TYPE_HASH, pubkeyHash, endorseChecksums)) {
×
908
                    NanopubLoader.loadStreamInParallel(stream, np -> {
×
909
                        try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
910
                            loadNanopub(ws, np, pubkeyHash, ENDORSE_TYPE);
×
911
                            totalLoaded.incrementAndGet();
×
912
                        }
913
                    });
×
914
                }
915

916
                Document de = new Document("pubkey", pubkeyHash).append("type", ENDORSE_TYPE_HASH);
×
917
                if (has(s, "lists", de)) {
×
918
                    set(s, "lists", de.append("status", loaded.getValue()));
×
919
                } else {
920
                    insert(s, "lists", de.append("status", loaded.getValue()));
×
921
                }
922

923
                Document df = new Document("pubkey", pubkeyHash).append("type", "$");
×
924
                if (!has(s, "lists", df)) insert(s, "lists", df.append("status", encountered.getValue()));
×
925
            }
×
926

927
            // Phase 2: Process encountered full lists (if budget remains)
928
            while (totalLoaded.get() < BATCH_SIZE) {
×
929
                Document df = getOne(s, "lists", new Document("type", "$").append("status", encountered.getValue()));
×
930
                if (df == null) break;
×
931

932
                final String pubkeyHash = df.getString("pubkey");
×
933
                log.info("Optional full loading: {}", pubkeyHash);
×
934

935
                // Load per covered type (or "$" if no restriction) with checksum skip-ahead
936
                for (String typeHash : getLoadTypeHashes(s, pubkeyHash)) {
×
937
                    String checksums = buildChecksumFallbacks(s, pubkeyHash, typeHash);
×
938
                    try (var stream = NanopubLoader.retrieveNanopubsFromPeers(typeHash, pubkeyHash, checksums)) {
×
939
                        NanopubLoader.loadStreamInParallel(stream, np -> {
×
940
                            if (!CoverageFilter.isCovered(np)) return;
×
941
                            try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
942
                                loadNanopub(ws, np, pubkeyHash, "$");
×
943
                                totalLoaded.incrementAndGet();
×
944
                            }
945
                        });
×
946
                    }
947
                }
×
948

949
                set(s, "lists", df.append("status", loaded.getValue()));
×
950

951
                // Backfill nanopubs stored locally during the transitional period (i.e. before
952
                // the $ list was loaded). Such nanopubs were stored in the nanopubs collection by
953
                // simpleLoad() but never added to listEntries; add them to the $ list now.
954
                log.info("Backfilling locally stored nanopubs for pubkey: {}", pubkeyHash);
×
955
                try (MongoCursor<Document> npCursor = collection(Collection.NANOPUBS.toString())
×
956
                        .find(s, new Document("pubkey", pubkeyHash)).cursor()) {
×
957
                    while (npCursor.hasNext()) {
×
958
                        String fullId = npCursor.next().getString("fullId");
×
959
                        if (fullId == null) continue;
×
960
                        try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
961
                            Nanopub np = NanopubLoader.retrieveLocalNanopub(ws, fullId);
×
962
                            if (np != null && CoverageFilter.isCovered(np)) {
×
963
                                loadNanopub(ws, np, pubkeyHash, "$");
×
964
                                totalLoaded.incrementAndGet();
×
965
                            }
966
                        } catch (Exception ex) {
×
967
                            log.info("Error backfilling nanopub {}: {}", fullId, ex.getMessage());
×
968
                        }
×
969
                    }
×
970
                }
971
            }
×
972

973
            if (totalLoaded.get() > 0) {
×
974
                log.info("Optional load batch completed: {} nanopubs across multiple pubkeys", totalLoaded.get());
×
975
            }
976

977
            if (prioritizeAllPubkeys()) {
×
978
                // Check if there are more pubkeys waiting to be processed
979
                boolean moreWork = has(s, "lists", new Document("type", INTRO_TYPE_HASH).append("status", encountered.getValue()))
×
980
                        || has(s, "lists", new Document("type", "$").append("status", encountered.getValue()));
×
981
                if (moreWork) {
×
982
                    // Continue processing without a full CHECK_NEW cycle in between.
983
                    // CHECK_NEW will run naturally once all encountered lists are processed.
984
                    schedule(s, RUN_OPTIONAL_LOAD.withDelay(10));
×
985
                } else {
986
                    schedule(s, CHECK_NEW.withDelay(500));
×
987
                }
988
            } else {
×
989
                // Throttled: yield to CHECK_NEW after each batch to prioritize approved pubkeys
990
                schedule(s, CHECK_NEW.withDelay(500));
×
991
            }
992
        }
×
993

994
    },
995

996
    CHECK_NEW {
33✔
997
        public void run(ClientSession s, Document taskDoc) {
998
            RegistryPeerConnector.checkPeers(s);
×
999
            // Keep legacy connection during transition period:
1000
            LegacyConnector.checkForNewNanopubs(s);
×
1001
            // TODO Somehow throttle the loading of such potentially non-approved nanopubs
1002

1003
            schedule(s, LOAD_FULL.withDelay(100));
×
1004
        }
×
1005

1006
        @Override
1007
        public boolean runAsTransaction() {
1008
            // Peer sync includes long-running streaming fetches that would exceed
1009
            // MongoDB's transaction timeout; each operation is individually safe.
1010
            return false;
×
1011
        }
1012

1013
    };
1014

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

1017
    public abstract void run(ClientSession s, Document taskDoc) throws Exception;
1018

1019
    public boolean runAsTransaction() {
1020
        return true;
×
1021
    }
1022

1023
    Document asDocument() {
1024
        return withDelay(0L);
12✔
1025
    }
1026

1027
    private Document withDelay(long delay) {
1028
        // TODO Rename "not-before" to "notBefore" for consistency with other field names
1029
        return new Document()
15✔
1030
                .append("not-before", System.currentTimeMillis() + delay)
21✔
1031
                .append("action", name());
6✔
1032
    }
1033

1034
    private Document with(String key, Object value) {
1035
        return asDocument().append(key, value);
×
1036
    }
1037

1038
    private static boolean prioritizeAllPubkeys() {
1039
        return "true".equals(System.getenv("REGISTRY_PRIORITIZE_ALL_PUBKEYS"));
×
1040
    }
1041

1042
    /**
1043
     * Returns the type hashes to load for a given pubkey. When coverage is unrestricted,
1044
     * returns just "$" (all types in one request). When restricted, returns each covered
1045
     * type hash for per-type fetching with checksum skip-ahead.
1046
     *
1047
     * TODO: Fetching "$" from peers with type restrictions will only return their covered
1048
     * types, not all types. To get full coverage, we'd need to fetch per-type from such peers.
1049
     * Additionally, checksum-based skip-ahead won't work correctly against such peers, because
1050
     * their "$" list has different checksums due to the differing type subset. This means full
1051
     * re-downloads on every cycle. Per-type fetching would solve both issues.
1052
     */
1053
    private static java.util.List<String> getLoadTypeHashes(ClientSession s, String pubkeyHash) {
1054
        if (CoverageFilter.coversAllTypes()) {
×
1055
            return java.util.List.of("$");
×
1056
        }
1057
        return java.util.List.copyOf(CoverageFilter.getCoveredTypeHashes());
×
1058
    }
1059

1060
    // TODO Move these to setting:
1061
    private static final int MAX_TRUST_PATH_DEPTH = 10;
1062
    private static final double MIN_TRUST_PATH_RATIO = 0.00000001;
1063
    //private static final double MIN_TRUST_PATH_RATIO = 0.01; // For testing
1064
    private static final int GLOBAL_QUOTA = Integer.parseInt(
12✔
1065
            Utils.getEnv("REGISTRY_GLOBAL_QUOTA", "1000000000"));
3✔
1066
    private static final int MIN_USER_QUOTA = Integer.parseInt(
12✔
1067
            Utils.getEnv("REGISTRY_MIN_USER_QUOTA", "1000"));
3✔
1068
    private static final int MAX_USER_QUOTA = Integer.parseInt(
12✔
1069
            Utils.getEnv("REGISTRY_MAX_USER_QUOTA", "100000"));
3✔
1070

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

1073
    private static volatile String currentTaskName;
1074
    private static volatile long currentTaskStartTime;
1075

1076
    public static String getCurrentTaskName() {
1077
        return currentTaskName;
×
1078
    }
1079

1080
    public static long getCurrentTaskStartTime() {
1081
        return currentTaskStartTime;
×
1082
    }
1083

1084
    /**
1085
     * The super important base entry point!
1086
     */
1087
    static void runTasks() {
1088
        try (ClientSession s = RegistryDB.getClient().startSession()) {
×
1089
            if (!RegistryDB.isInitialized(s)) {
×
1090
                schedule(s, INIT_DB); // does not yet execute, only schedules
×
1091
            }
1092

1093
            while (true) {
1094
                FindIterable<Document> taskResult = tasksCollection.find(s).sort(ascending("not-before"));
×
1095
                Document taskDoc = taskResult.first();
×
1096
                long sleepTime = 10;
×
1097
                if (taskDoc != null && taskDoc.getLong("not-before") < System.currentTimeMillis()) {
×
1098
                    Task task = valueOf(taskDoc.getString("action"));
×
1099
                    log.info("Running task: {}", task.name());
×
1100
                    if (task.runAsTransaction()) {
×
1101
                        try {
1102
                            s.startTransaction();
×
1103
                            log.info("Transaction started");
×
1104
                            runTask(task, taskDoc);
×
1105
                            s.commitTransaction();
×
1106
                            log.info("Transaction committed");
×
1107
                        } catch (Exception ex) {
×
1108
                            log.info("Aborting transaction", ex);
×
1109
                            abortTransaction(s, ex.getMessage());
×
1110
                            log.info("Transaction aborted");
×
1111
                            sleepTime = 1000;
×
1112
                        } finally {
1113
                            cleanTransactionWithRetry(s);
×
1114
                        }
×
1115
                    } else {
1116
                        try {
1117
                            runTask(task, taskDoc);
×
1118
                        } catch (Exception ex) {
×
1119
                            log.info("Transaction failed", ex);
×
1120
                        }
×
1121
                    }
1122
                }
1123
                try {
1124
                    Thread.sleep(sleepTime);
×
1125
                } catch (InterruptedException ex) {
×
1126
                    // ignore
1127
                }
×
1128
            }
×
1129
        }
1130
    }
1131

1132
    static void runTask(Task task, Document taskDoc) throws Exception {
1133
        try (ClientSession s = RegistryDB.getClient().startSession()) {
9✔
1134
            log.info("Executing task: {}", task.name());
15✔
1135
            currentTaskName = task.name();
9✔
1136
            currentTaskStartTime = System.currentTimeMillis();
6✔
1137
            task.run(s, taskDoc);
12✔
1138
            tasksCollection.deleteOne(s, eq("_id", taskDoc.get("_id")));
27✔
1139
            log.info("Task {} completed and removed from queue.", task.name());
15✔
1140
        } finally {
1141
            currentTaskName = null;
6✔
1142
        }
1143
    }
3✔
1144

1145
    public static void abortTransaction(ClientSession mongoSession, String message) {
1146
        boolean successful = false;
×
1147
        while (!successful) {
×
1148
            try {
1149
                if (mongoSession.hasActiveTransaction()) {
×
1150
                    mongoSession.abortTransaction();
×
1151
                }
1152
                successful = true;
×
1153
            } catch (Exception ex) {
×
1154
                log.info("Aborting transaction failed. ", ex);
×
1155
                try {
1156
                    Thread.sleep(1000);
×
1157
                } catch (InterruptedException iex) {
×
1158
                    // ignore
1159
                }
×
1160
            }
×
1161
        }
1162
    }
×
1163

1164
    public synchronized static void cleanTransactionWithRetry(ClientSession mongoSession) {
1165
        boolean successful = false;
×
1166
        while (!successful) {
×
1167
            try {
1168
                if (mongoSession.hasActiveTransaction()) {
×
1169
                    mongoSession.abortTransaction();
×
1170
                }
1171
                successful = true;
×
1172
            } catch (Exception ex) {
×
1173
                log.info("Cleaning transaction failed. ", ex);
×
1174
                try {
1175
                    Thread.sleep(1000);
×
1176
                } catch (InterruptedException iex) {
×
1177
                    // ignore
1178
                }
×
1179
            }
×
1180
        }
1181
    }
×
1182

1183
    private static IntroNanopub getAgentIntro(ClientSession mongoSession, String nanopubId) {
1184
        IntroNanopub agentIntro = new IntroNanopub(NanopubLoader.retrieveNanopub(mongoSession, nanopubId));
×
1185
        if (agentIntro.getUser() == null) return null;
×
1186
        loadNanopub(mongoSession, agentIntro.getNanopub());
×
1187
        return agentIntro;
×
1188
    }
1189

1190
    private static void setServerStatus(ClientSession mongoSession, ServerStatus status) {
1191
        setValue(mongoSession, Collection.SERVER_INFO.toString(), "status", status.toString());
21✔
1192
    }
3✔
1193

1194
    private static ServerStatus getServerStatus(ClientSession mongoSession) {
1195
        Object status = getValue(mongoSession, Collection.SERVER_INFO.toString(), "status");
18✔
1196
        if (status == null) {
6!
1197
            throw new RuntimeException("Illegal DB state: serverInfo status unavailable");
×
1198
        }
1199
        return ServerStatus.valueOf(status.toString());
12✔
1200
    }
1201

1202
    private static void schedule(ClientSession mongoSession, Task task) {
1203
        schedule(mongoSession, task.asDocument());
12✔
1204
    }
3✔
1205

1206
    private static void schedule(ClientSession mongoSession, Document taskDoc) {
1207
        log.info("Scheduling task: {}", taskDoc.getString("action"));
18✔
1208
        tasksCollection.insertOne(mongoSession, taskDoc);
12✔
1209
    }
3✔
1210

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