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

knowledgepixels / nanopub-registry / 24089041807

07 Apr 2026 03:14PM UTC coverage: 33.374% (+0.5%) from 32.913%
24089041807

push

github

web-flow
Merge pull request #96 from knowledgepixels/feat/agent-quota-enforcement

feat: enforce agent/pubkey quota restrictions

273 of 900 branches covered (30.33%)

Branch coverage included in aggregate %.

809 of 2342 relevant lines covered (34.54%)

5.77 hits per line

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

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

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

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

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

34
public enum Task implements Serializable {
6✔
35

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

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

49
    },
50

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

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

66
    },
67

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

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

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

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

95
    },
96

97
    INIT_COLLECTIONS {
33✔
98

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

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

108
            IndexInitializer.initLoadingCollections(s);
×
109

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

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

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

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

154
                );
155

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

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

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

182
    },
183

184
    LOAD_DECLARATIONS {
33✔
185

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

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

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

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

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

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

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

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

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

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

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

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

268
    },
269

270
    EXPAND_TRUST_PATHS {
33✔
271

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

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

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

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

284
            if (d != null) {
×
285

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

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

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

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

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

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

342
            } else {
×
343

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

346
            }
347

348
        }
×
349

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

366
    },
367

368
    LOAD_CORE {
33✔
369

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

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

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

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

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

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

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

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

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

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

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

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

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

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

494
        }
×
495

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

511
    },
512

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

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

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

530
        }
×
531

532
    },
533

534
    CALCULATE_TRUST_SCORES {
33✔
535

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

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

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

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

584
        }
×
585

586
    },
587

588
    AGGREGATE_AGENTS {
33✔
589

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

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

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

620
        }
×
621

622
    },
623

624
    ASSIGN_PUBKEYS {
33✔
625

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

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

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

647
        }
×
648

649
    },
650

651
    DETERMINE_UPDATES {
33✔
652

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

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

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

672
        }
×
673

674
    },
675

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

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

687
    },
688

689
    RELEASE_DATA {
33✔
690
        public void run(ClientSession s, Document taskDoc) {
691
            ServerStatus status = getServerStatus(s);
×
692

693
            String newTrustStateHash = taskDoc.get("newTrustStateHash").toString();
×
694
            String previousTrustStateHash = taskDoc.getString("previousTrustStateHash");  // may be null
×
695

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

702
            if (previousTrustStateHash == null || !previousTrustStateHash.equals(newTrustStateHash)) {
×
703
                increaseStateCounter(s);
×
704
                setValue(s, Collection.SERVER_INFO.toString(), "trustStateHash", newTrustStateHash);
×
705
                insert(s, "debug_trustPaths", new Document()
×
706
                        .append("trustStateTxt", DebugPage.getTrustPathsTxt(s))
×
707
                        .append("trustStateHash", newTrustStateHash)
×
708
                        .append("trustStateCounter", getValue(s, Collection.SERVER_INFO.toString(), "trustStateCounter"))
×
709
                );
710
            }
711

712
            if (status == coreLoading) {
×
713
                setServerStatus(s, coreReady);
×
714
            } else {
715
                setServerStatus(s, ready);
×
716
            }
717

718
            // Run update after 1h:
719
            schedule(s, UPDATE.withDelay(60 * 60 * 1000));
×
720
        }
×
721

722
    },
723

724
    UPDATE {
33✔
725
        public void run(ClientSession s, Document taskDoc) {
726
            ServerStatus status = getServerStatus(s);
×
727
            if (status == ready || status == coreReady) {
×
728
                setServerStatus(s, updating);
×
729
                schedule(s, INIT_COLLECTIONS);
×
730
            } else {
731
                log.info("Postponing update; currently in status {}", status);
×
732
                schedule(s, UPDATE.withDelay(10 * 60 * 1000));
×
733
            }
734

735
        }
×
736

737
    },
738

739
    LOAD_FULL {
33✔
740
        public void run(ClientSession s, Document taskDoc) {
741
            if ("false".equals(System.getenv("REGISTRY_PERFORM_FULL_LOAD"))) return;
15!
742

743
            ServerStatus status = getServerStatus(s);
9✔
744
            if (status != coreReady && status != ready && status != updating) {
27!
745
                long retryDelay = "false".equals(System.getenv("REGISTRY_ENABLE_TRUST_CALCULATION")) ? 100 : 60 * 1000;
21!
746
                log.info("Server currently not ready; checking again later");
9✔
747
                schedule(s, LOAD_FULL.withDelay(retryDelay));
15✔
748
                return;
3✔
749
            }
750

751
            Document a = getOne(s, Collection.ACCOUNTS.toString(), new DbEntryWrapper(toLoad).getDocument());
×
752
            if (a == null) {
×
753
                log.info("Nothing to load");
×
754
                if (status == coreReady) {
×
755
                    log.info("Full load finished");
×
756
                    setServerStatus(s, ready);
×
757
                }
758
                log.info("Scheduling optional loading checks");
×
759
                schedule(s, RUN_OPTIONAL_LOAD.withDelay(100));
×
760
            } else {
761
                final String ph = a.getString("pubkey");
×
762
                boolean quotaReached = false;
×
763
                if (!ph.equals("$")) {
×
764
                    if (!AgentFilter.isAllowed(s, ph)) {
×
765
                        log.info("Skipping pubkey {} (not covered by agent filter)", ph);
×
766
                        set(s, Collection.ACCOUNTS.toString(), a.append("status", skipped.getValue()));
×
767
                        schedule(s, LOAD_FULL.withDelay(100));
×
768
                        return;
×
769
                    }
770
                    if (AgentFilter.isOverQuota(s, ph)) {
×
771
                        log.info("Skipping pubkey {} (quota exceeded)", ph);
×
772
                        quotaReached = true;
×
773
                    } else {
774
                        long startTime = System.nanoTime();
×
775
                        AtomicLong totalLoaded = new AtomicLong(0);
×
776

777
                        // Load per covered type (or "$" if no restriction) with checksum skip-ahead
778
                        for (String typeHash : getLoadTypeHashes(s, ph)) {
×
779
                            String checksums = buildChecksumFallbacks(s, ph, typeHash);
×
780
                            try (var stream = NanopubLoader.retrieveNanopubsFromPeers(typeHash, ph, checksums)) {
×
781
                                NanopubLoader.loadStreamInParallel(stream, np -> {
×
782
                                    if (!CoverageFilter.isCovered(np)) return;
×
783
                                    try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
784
                                        if (!AgentFilter.isOverQuota(ws, ph)) {
×
785
                                            loadNanopub(ws, np, ph, "$");
×
786
                                            totalLoaded.incrementAndGet();
×
787
                                        }
788
                                    }
789
                                });
×
790
                            }
791
                        }
×
792

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

797
                        if (AgentFilter.isOverQuota(s, ph)) {
×
798
                            quotaReached = true;
×
799
                        }
800
                    }
801
                }
802

803
                Document l = getOne(s, "lists", new Document().append("pubkey", ph).append("type", "$"));
×
804
                if (l != null) set(s, "lists", l.append("status", loaded.getValue()));
×
805
                EntryStatus accountStatus = quotaReached ? capped : loaded;
×
806
                int effectiveQuota = AgentFilter.getQuota(s, ph);
×
807
                if (effectiveQuota >= 0) {
×
808
                    a.append("quota", effectiveQuota);
×
809
                }
810
                set(s, Collection.ACCOUNTS.toString(), a.append("status", accountStatus.getValue()));
×
811

812
                schedule(s, LOAD_FULL.withDelay(100));
×
813
            }
814
        }
×
815

816
        @Override
817
        public boolean runAsTransaction() {
818
            // TODO Make this a transaction once we connect to other Nanopub Registry instances:
819
            return false;
×
820
        }
821

822
    },
823

824
    RUN_OPTIONAL_LOAD {
33✔
825

826
        private static final int BATCH_SIZE = Integer.parseInt(
15✔
827
                Utils.getEnv("REGISTRY_OPTIONAL_LOAD_BATCH_SIZE", "100"));
3✔
828

829
        public void run(ClientSession s, Document taskDoc) {
830
            if ("false".equals(System.getenv("REGISTRY_ENABLE_OPTIONAL_LOAD"))) {
×
831
                schedule(s, CHECK_NEW.withDelay(500));
×
832
                return;
×
833
            }
834

835
            AtomicLong totalLoaded = new AtomicLong(0);
×
836

837
            // Phase 1: Process encountered intro lists (core loading)
838
            while (totalLoaded.get() < BATCH_SIZE) {
×
839
                Document di = getOne(s, "lists", new Document("type", INTRO_TYPE_HASH).append("status", encountered.getValue()));
×
840
                if (di == null) break;
×
841

842
                final String pubkeyHash = di.getString("pubkey");
×
843
                Validate.notNull(pubkeyHash);
×
844
                log.info("Optional core loading: {}", pubkeyHash);
×
845

846
                String introChecksums = buildChecksumFallbacks(s, pubkeyHash, INTRO_TYPE_HASH);
×
847
                try (var stream = NanopubLoader.retrieveNanopubsFromPeers(INTRO_TYPE_HASH, pubkeyHash, introChecksums)) {
×
848
                    NanopubLoader.loadStreamInParallel(stream, np -> {
×
849
                        try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
850
                            loadNanopub(ws, np, pubkeyHash, INTRO_TYPE);
×
851
                            totalLoaded.incrementAndGet();
×
852
                        }
853
                    });
×
854
                }
855
                set(s, "lists", di.append("status", loaded.getValue()));
×
856

857
                String endorseChecksums = buildChecksumFallbacks(s, pubkeyHash, ENDORSE_TYPE_HASH);
×
858
                try (var stream = NanopubLoader.retrieveNanopubsFromPeers(ENDORSE_TYPE_HASH, pubkeyHash, endorseChecksums)) {
×
859
                    NanopubLoader.loadStreamInParallel(stream, np -> {
×
860
                        try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
861
                            loadNanopub(ws, np, pubkeyHash, ENDORSE_TYPE);
×
862
                            totalLoaded.incrementAndGet();
×
863
                        }
864
                    });
×
865
                }
866

867
                Document de = new Document("pubkey", pubkeyHash).append("type", ENDORSE_TYPE_HASH);
×
868
                if (has(s, "lists", de)) {
×
869
                    set(s, "lists", de.append("status", loaded.getValue()));
×
870
                } else {
871
                    insert(s, "lists", de.append("status", loaded.getValue()));
×
872
                }
873

874
                Document df = new Document("pubkey", pubkeyHash).append("type", "$");
×
875
                if (!has(s, "lists", df)) insert(s, "lists", df.append("status", encountered.getValue()));
×
876
            }
×
877

878
            // Phase 2: Process encountered full lists (if budget remains)
879
            while (totalLoaded.get() < BATCH_SIZE) {
×
880
                Document df = getOne(s, "lists", new Document("type", "$").append("status", encountered.getValue()));
×
881
                if (df == null) break;
×
882

883
                final String pubkeyHash = df.getString("pubkey");
×
884
                log.info("Optional full loading: {}", pubkeyHash);
×
885

886
                // Load per covered type (or "$" if no restriction) with checksum skip-ahead
887
                for (String typeHash : getLoadTypeHashes(s, pubkeyHash)) {
×
888
                    String checksums = buildChecksumFallbacks(s, pubkeyHash, typeHash);
×
889
                    try (var stream = NanopubLoader.retrieveNanopubsFromPeers(typeHash, pubkeyHash, checksums)) {
×
890
                        NanopubLoader.loadStreamInParallel(stream, np -> {
×
891
                            if (!CoverageFilter.isCovered(np)) return;
×
892
                            try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
893
                                loadNanopub(ws, np, pubkeyHash, "$");
×
894
                                totalLoaded.incrementAndGet();
×
895
                            }
896
                        });
×
897
                    }
898
                }
×
899

900
                set(s, "lists", df.append("status", loaded.getValue()));
×
901
            }
×
902

903
            if (totalLoaded.get() > 0) {
×
904
                log.info("Optional load batch completed: {} nanopubs across multiple pubkeys", totalLoaded.get());
×
905
            }
906

907
            if (prioritizeAllPubkeys()) {
×
908
                // Check if there are more pubkeys waiting to be processed
909
                boolean moreWork = has(s, "lists", new Document("type", INTRO_TYPE_HASH).append("status", encountered.getValue()))
×
910
                        || has(s, "lists", new Document("type", "$").append("status", encountered.getValue()));
×
911
                if (moreWork) {
×
912
                    // Continue processing without a full CHECK_NEW cycle in between.
913
                    // CHECK_NEW will run naturally once all encountered lists are processed.
914
                    schedule(s, RUN_OPTIONAL_LOAD.withDelay(10));
×
915
                } else {
916
                    schedule(s, CHECK_NEW.withDelay(500));
×
917
                }
918
            } else {
×
919
                // Throttled: yield to CHECK_NEW after each batch to prioritize approved pubkeys
920
                schedule(s, CHECK_NEW.withDelay(500));
×
921
            }
922
        }
×
923

924
    },
925

926
    CHECK_NEW {
33✔
927
        public void run(ClientSession s, Document taskDoc) {
928
            RegistryPeerConnector.checkPeers(s);
×
929
            // Keep legacy connection during transition period:
930
            LegacyConnector.checkForNewNanopubs(s);
×
931
            // TODO Somehow throttle the loading of such potentially non-approved nanopubs
932

933
            schedule(s, LOAD_FULL.withDelay(100));
×
934
        }
×
935

936
        @Override
937
        public boolean runAsTransaction() {
938
            // Peer sync includes long-running streaming fetches that would exceed
939
            // MongoDB's transaction timeout; each operation is individually safe.
940
            return false;
×
941
        }
942

943
    };
944

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

947
    public abstract void run(ClientSession s, Document taskDoc) throws Exception;
948

949
    public boolean runAsTransaction() {
950
        return true;
×
951
    }
952

953
    Document asDocument() {
954
        return withDelay(0L);
12✔
955
    }
956

957
    private Document withDelay(long delay) {
958
        // TODO Rename "not-before" to "notBefore" for consistency with other field names
959
        return new Document()
15✔
960
                .append("not-before", System.currentTimeMillis() + delay)
21✔
961
                .append("action", name());
6✔
962
    }
963

964
    private Document with(String key, Object value) {
965
        return asDocument().append(key, value);
×
966
    }
967

968
    private static boolean prioritizeAllPubkeys() {
969
        return "true".equals(System.getenv("REGISTRY_PRIORITIZE_ALL_PUBKEYS"));
×
970
    }
971

972
    /**
973
     * Returns the type hashes to load for a given pubkey. When coverage is unrestricted,
974
     * returns just "$" (all types in one request). When restricted, returns each covered
975
     * type hash for per-type fetching with checksum skip-ahead.
976
     *
977
     * TODO: Fetching "$" from peers with type restrictions will only return their covered
978
     * types, not all types. To get full coverage, we'd need to fetch per-type from such peers.
979
     * Additionally, checksum-based skip-ahead won't work correctly against such peers, because
980
     * their "$" list has different checksums due to the differing type subset. This means full
981
     * re-downloads on every cycle. Per-type fetching would solve both issues.
982
     */
983
    private static java.util.List<String> getLoadTypeHashes(ClientSession s, String pubkeyHash) {
984
        if (CoverageFilter.coversAllTypes()) {
×
985
            return java.util.List.of("$");
×
986
        }
987
        return java.util.List.copyOf(CoverageFilter.getCoveredTypeHashes());
×
988
    }
989

990
    // TODO Move these to setting:
991
    private static final int MAX_TRUST_PATH_DEPTH = 10;
992
    private static final double MIN_TRUST_PATH_RATIO = 0.00000001;
993
    //private static final double MIN_TRUST_PATH_RATIO = 0.01; // For testing
994
    private static final int GLOBAL_QUOTA = Integer.parseInt(
12✔
995
            Utils.getEnv("REGISTRY_GLOBAL_QUOTA", "1000000000"));
3✔
996
    private static final int MIN_USER_QUOTA = Integer.parseInt(
12✔
997
            Utils.getEnv("REGISTRY_MIN_USER_QUOTA", "1000"));
3✔
998
    private static final int MAX_USER_QUOTA = Integer.parseInt(
12✔
999
            Utils.getEnv("REGISTRY_MAX_USER_QUOTA", "100000"));
3✔
1000

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

1003
    private static volatile String currentTaskName;
1004
    private static volatile long currentTaskStartTime;
1005

1006
    public static String getCurrentTaskName() {
1007
        return currentTaskName;
×
1008
    }
1009

1010
    public static long getCurrentTaskStartTime() {
1011
        return currentTaskStartTime;
×
1012
    }
1013

1014
    /**
1015
     * The super important base entry point!
1016
     */
1017
    static void runTasks() {
1018
        try (ClientSession s = RegistryDB.getClient().startSession()) {
×
1019
            if (!RegistryDB.isInitialized(s)) {
×
1020
                schedule(s, INIT_DB); // does not yet execute, only schedules
×
1021
            }
1022

1023
            while (true) {
1024
                FindIterable<Document> taskResult = tasksCollection.find(s).sort(ascending("not-before"));
×
1025
                Document taskDoc = taskResult.first();
×
1026
                long sleepTime = 10;
×
1027
                if (taskDoc != null && taskDoc.getLong("not-before") < System.currentTimeMillis()) {
×
1028
                    Task task = valueOf(taskDoc.getString("action"));
×
1029
                    log.info("Running task: {}", task.name());
×
1030
                    if (task.runAsTransaction()) {
×
1031
                        try {
1032
                            s.startTransaction();
×
1033
                            log.info("Transaction started");
×
1034
                            runTask(task, taskDoc);
×
1035
                            s.commitTransaction();
×
1036
                            log.info("Transaction committed");
×
1037
                        } catch (Exception ex) {
×
1038
                            log.info("Aborting transaction", ex);
×
1039
                            abortTransaction(s, ex.getMessage());
×
1040
                            log.info("Transaction aborted");
×
1041
                            sleepTime = 1000;
×
1042
                        } finally {
1043
                            cleanTransactionWithRetry(s);
×
1044
                        }
×
1045
                    } else {
1046
                        try {
1047
                            runTask(task, taskDoc);
×
1048
                        } catch (Exception ex) {
×
1049
                            log.info("Transaction failed", ex);
×
1050
                        }
×
1051
                    }
1052
                }
1053
                try {
1054
                    Thread.sleep(sleepTime);
×
1055
                } catch (InterruptedException ex) {
×
1056
                    // ignore
1057
                }
×
1058
            }
×
1059
        }
1060
    }
1061

1062
    static void runTask(Task task, Document taskDoc) throws Exception {
1063
        try (ClientSession s = RegistryDB.getClient().startSession()) {
9✔
1064
            log.info("Executing task: {}", task.name());
15✔
1065
            currentTaskName = task.name();
9✔
1066
            currentTaskStartTime = System.currentTimeMillis();
6✔
1067
            task.run(s, taskDoc);
12✔
1068
            tasksCollection.deleteOne(s, eq("_id", taskDoc.get("_id")));
27✔
1069
            log.info("Task {} completed and removed from queue.", task.name());
15✔
1070
        } finally {
1071
            currentTaskName = null;
6✔
1072
        }
1073
    }
3✔
1074

1075
    public static void abortTransaction(ClientSession mongoSession, String message) {
1076
        boolean successful = false;
×
1077
        while (!successful) {
×
1078
            try {
1079
                if (mongoSession.hasActiveTransaction()) {
×
1080
                    mongoSession.abortTransaction();
×
1081
                }
1082
                successful = true;
×
1083
            } catch (Exception ex) {
×
1084
                log.info("Aborting transaction failed. ", ex);
×
1085
                try {
1086
                    Thread.sleep(1000);
×
1087
                } catch (InterruptedException iex) {
×
1088
                    // ignore
1089
                }
×
1090
            }
×
1091
        }
1092
    }
×
1093

1094
    public synchronized static void cleanTransactionWithRetry(ClientSession mongoSession) {
1095
        boolean successful = false;
×
1096
        while (!successful) {
×
1097
            try {
1098
                if (mongoSession.hasActiveTransaction()) {
×
1099
                    mongoSession.abortTransaction();
×
1100
                }
1101
                successful = true;
×
1102
            } catch (Exception ex) {
×
1103
                log.info("Cleaning transaction failed. ", ex);
×
1104
                try {
1105
                    Thread.sleep(1000);
×
1106
                } catch (InterruptedException iex) {
×
1107
                    // ignore
1108
                }
×
1109
            }
×
1110
        }
1111
    }
×
1112

1113
    private static IntroNanopub getAgentIntro(ClientSession mongoSession, String nanopubId) {
1114
        IntroNanopub agentIntro = new IntroNanopub(NanopubLoader.retrieveNanopub(mongoSession, nanopubId));
×
1115
        if (agentIntro.getUser() == null) return null;
×
1116
        loadNanopub(mongoSession, agentIntro.getNanopub());
×
1117
        return agentIntro;
×
1118
    }
1119

1120
    private static void setServerStatus(ClientSession mongoSession, ServerStatus status) {
1121
        setValue(mongoSession, Collection.SERVER_INFO.toString(), "status", status.toString());
21✔
1122
    }
3✔
1123

1124
    private static ServerStatus getServerStatus(ClientSession mongoSession) {
1125
        Object status = getValue(mongoSession, Collection.SERVER_INFO.toString(), "status");
18✔
1126
        if (status == null) {
6!
1127
            throw new RuntimeException("Illegal DB state: serverInfo status unavailable");
×
1128
        }
1129
        return ServerStatus.valueOf(status.toString());
12✔
1130
    }
1131

1132
    private static void schedule(ClientSession mongoSession, Task task) {
1133
        schedule(mongoSession, task.asDocument());
12✔
1134
    }
3✔
1135

1136
    private static void schedule(ClientSession mongoSession, Document taskDoc) {
1137
        log.info("Scheduling task: {}", taskDoc.getString("action"));
18✔
1138
        tasksCollection.insertOne(mongoSession, taskDoc);
12✔
1139
    }
3✔
1140

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