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

knowledgepixels / nanopub-registry / 25000775168

27 Apr 2026 02:25PM UTC coverage: 32.001% (+0.2%) from 31.808%
25000775168

Pull #113

github

web-flow
Merge ac3b547ae into 377ce4430
Pull Request #113: feat: stamp foaf:name + dct:created of declaring intro on accounts

294 of 1014 branches covered (28.99%)

Branch coverage included in aggregate %.

851 of 2564 relevant lines covered (33.19%)

5.5 hits per line

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

11.19
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.SimpleTimestampPattern;
16
import org.nanopub.extra.index.IndexUtils;
17
import org.nanopub.extra.index.NanopubIndex;
18
import org.nanopub.extra.security.KeyDeclaration;
19
import org.nanopub.extra.setting.IntroNanopub;
20
import org.nanopub.extra.setting.NanopubSetting;
21
import org.slf4j.Logger;
22
import org.slf4j.LoggerFactory;
23

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

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

36
public enum Task implements Serializable {
6✔
37

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

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

51
    },
52

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

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

68
    },
69

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

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

88
            if (!"false".equals(System.getenv("REGISTRY_PERFORM_FULL_LOAD"))) {
15!
89
                schedule(s, LOAD_FULL);
9✔
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
            while (true) {
208
                Document d = getOne(s, "endorsements_loading",
×
209
                        new DbEntryWrapper(toRetrieve).getDocument());
×
210
                if (d == null) break;
×
211

212
                IntroNanopub agentIntro = getAgentIntro(s, d.getString("endorsedNanopub"));
×
213
                if (agentIntro != null) {
×
214
                    String agentId = agentIntro.getUser().stringValue();
×
215
                    // foaf:name + dct:created of the intro nanopub. Same name applies to every
216
                    // KeyDeclaration in the intro, so resolve once outside the inner loop.
217
                    String introName = Utils.extractIntroName(agentIntro);
×
218
                    Calendar introCreatedCal = SimpleTimestampPattern.getCreationTime(agentIntro.getNanopub());
×
219
                    Date introCreatedAt = (introCreatedCal == null) ? null : introCreatedCal.getTime();
×
220

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

240
                        Document agent = new Document("agent", agentId).append("pubkey", agentPubkey);
×
241
                        Document existing = collection("accounts_loading").find(s, agent).first();
×
242
                        if (existing == null) {
×
243
                            insert(s, "accounts_loading", agent
×
244
                                    .append("status", seen.getValue())
×
245
                                    .append("depth", depth)
×
246
                                    .append("name", introName)
×
247
                                    .append("nameCreatedAt", introCreatedAt));
×
248
                        } else if (introName != null) {
×
249
                            // Per-(agent, pubkey) name policy: keep the name from the intro
250
                            // with the latest dct:created. First write wins when no current
251
                            // timestamp exists; otherwise compare and replace iff strictly newer.
252
                            Date currentCreatedAt = existing.getDate("nameCreatedAt");
×
253
                            if (currentCreatedAt == null
×
254
                                    || (introCreatedAt != null && introCreatedAt.after(currentCreatedAt))) {
×
255
                                set(s, "accounts_loading", existing
×
256
                                        .append("name", introName)
×
257
                                        .append("nameCreatedAt", introCreatedAt));
×
258
                            }
259
                        }
260
                    }
×
261

262
                    set(s, "endorsements_loading", d.append("status", retrieved.getValue()));
×
263
                } else {
×
264
                    set(s, "endorsements_loading", d.append("status", discarded.getValue()));
×
265
                }
266
            }
×
267
            schedule(s, EXPAND_TRUST_PATHS.with("depth", depth));
×
268
        }
×
269

270
        // At the end of this step, the key declarations in the agent
271
        // introductions are loaded and the corresponding trust edges
272
        // established:
273
        // ------------------------------------------------------------
274
        //
275
        //        o      ----endorses----> [intro]
276
        //   --> /#\  /o\___                o
277
        //       / \  \_/^^^ ---trusts---> /#\  /o\___
278
        //        (visited)                / \  \_/^^^
279
        //                                   (seen)
280
        //
281
        //   ========[X] trust path
282
        //
283
        // ------------------------------------------------------------
284
        // Only one trust edge per introduction is shown here, but
285
        // there can be several.
286

287
    },
288

289
    EXPAND_TRUST_PATHS {
33✔
290

291
        // DB read from: accounts, trustPaths, trustEdges
292
        // DB write to:  accounts, trustPaths
293

294
        public void run(ClientSession s, Document taskDoc) {
295

296
            int depth = taskDoc.getInteger("depth");
×
297

298
            while (true) {
299
                Document d = getOne(s, "accounts_loading",
×
300
                        new Document("status", visited.getValue())
×
301
                                .append("depth", depth - 1)
×
302
                );
303
                if (d == null) break;
×
304

305
                String agentId = d.getString("agent");
×
306
                Validate.notNull(agentId);
×
307
                String pubkeyHash = d.getString("pubkey");
×
308
                Validate.notNull(pubkeyHash);
×
309

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

314
                if (trustPath == null) {
×
315
                    // Check it again in next iteration:
316
                    set(s, "accounts_loading", d.append("depth", depth));
×
317
                } else {
318
                    // Only first matching trust path is considered
319

320
                    Map<String, Document> newPaths = new HashMap<>();
×
321
                    Map<String, Set<String>> pubkeySets = new HashMap<>();
×
322
                    String currentSetting = getValue(s, Collection.SETTING.toString(), "current").toString();
×
323

324
                    try (MongoCursor<Document> edgeCursor = get(s, "trustEdges",
×
325
                            new Document("fromAgent", agentId)
326
                                    .append("fromPubkey", pubkeyHash)
×
327
                                    .append("invalidated", false)
×
328
                    )) {
329
                        while (edgeCursor.hasNext()) {
×
330
                            Document e = edgeCursor.next();
×
331

332
                            String agent = e.getString("toAgent");
×
333
                            Validate.notNull(agent);
×
334
                            String pubkey = e.getString("toPubkey");
×
335
                            Validate.notNull(pubkey);
×
336
                            String pathId = trustPath.getString("_id") + " " + agent + "|" + pubkey;
×
337
                            newPaths.put(pathId,
×
338
                                    new Document("_id", pathId)
339
                                            .append("sorthash", Utils.getHash(currentSetting + " " + pathId))
×
340
                                            .append("agent", agent)
×
341
                                            .append("pubkey", pubkey)
×
342
                                            .append("depth", depth)
×
343
                                            .append("type", "extended")
×
344
                            );
345
                            if (!pubkeySets.containsKey(agent)) pubkeySets.put(agent, new HashSet<>());
×
346
                            pubkeySets.get(agent).add(pubkey);
×
347
                        }
×
348
                    }
349
                    for (String pathId : newPaths.keySet()) {
×
350
                        Document pd = newPaths.get(pathId);
×
351
                        // first divide by agents; then for each agent, divide by number of pubkeys:
352
                        double newRatio = (trustPath.getDouble("ratio") * 0.9) / pubkeySets.size() / pubkeySets.get(pd.getString("agent")).size();
×
353
                        insert(s, "trustPaths_loading", pd.append("ratio", newRatio));
×
354
                    }
×
355
                    // Retain only 10% of the ratio — the other 90% was distributed to children
356
                    double retainedRatio = trustPath.getDouble("ratio") * 0.1;
×
357
                    set(s, "trustPaths_loading", trustPath.append("type", "primary").append("ratio", retainedRatio));
×
358
                    set(s, "accounts_loading", d.append("status", expanded.getValue()));
×
359
                }
360
            }
×
361
            schedule(s, LOAD_CORE.with("depth", depth).append("load-count", 0));
×
362

363
        }
×
364

365
        // At the end of this step, trust paths are updated to include
366
        // the new accounts:
367
        // ------------------------------------------------------------
368
        //
369
        //         o      ----endorses----> [intro]
370
        //    --> /#\  /o\___                o
371
        //        / \  \_/^^^ ---trusts---> /#\  /o\___
372
        //        (expanded)                / \  \_/^^^
373
        //                                    (seen)
374
        //
375
        //    ========[X]=====================[X+1] trust path
376
        //
377
        // ------------------------------------------------------------
378
        // Only one trust path is shown here, but they branch out if
379
        // several trust edges are present.
380

381
    },
382

383
    LOAD_CORE {
33✔
384

385
        // From here on, we refocus on the head of the trust paths:
386
        // ------------------------------------------------------------
387
        //
388
        //         o
389
        //    --> /#\  /o\___
390
        //        / \  \_/^^^
391
        //          (seen)
392
        //
393
        //    ========[X] trust path
394
        //
395
        // ------------------------------------------------------------
396

397
        // DB read from: accounts, trustPaths, endorsements, lists
398
        // DB write to:  accounts, endorsements, lists
399

400
        public void run(ClientSession s, Document taskDoc) {
401

402
            int depth = taskDoc.getInteger("depth");
×
403
            int loadCount = taskDoc.getInteger("load-count");
×
404

405
            Document agentAccount = getOne(s, "accounts_loading",
×
406
                    new Document("depth", depth).append("status", seen.getValue()));
×
407
            final String agentId;
408
            final String pubkeyHash;
409
            final Document trustPath;
410
            if (agentAccount != null) {
×
411
                agentId = agentAccount.getString("agent");
×
412
                Validate.notNull(agentId);
×
413
                pubkeyHash = agentAccount.getString("pubkey");
×
414
                Validate.notNull(pubkeyHash);
×
415
                trustPath = getOne(s, "trustPaths_loading",
×
416
                        new Document("depth", depth)
×
417
                                .append("agent", agentId)
×
418
                                .append("pubkey", pubkeyHash)
×
419
                );
420
            } else {
421
                agentId = null;
×
422
                pubkeyHash = null;
×
423
                trustPath = null;
×
424
            }
425

426
            if (agentAccount == null) {
×
427
                schedule(s, FINISH_ITERATION.with("depth", depth).append("load-count", loadCount));
×
428
            } else if (trustPath == null) {
×
429
                // Account was seen but has no trust path at this depth; skip it
430
                set(s, "accounts_loading", agentAccount.append("status", skipped.getValue()));
×
431
                schedule(s, LOAD_CORE.with("depth", depth).append("load-count", loadCount));
×
432
            } else if (trustPath.getDouble("ratio") < MIN_TRUST_PATH_RATIO) {
×
433
                set(s, "accounts_loading", agentAccount.append("status", skipped.getValue()));
×
434
                Document d = new Document("pubkey", pubkeyHash).append("type", INTRO_TYPE_HASH);
×
435
                if (!has(s, "lists", d)) {
×
436
                    insert(s, "lists", d.append("status", encountered.getValue()));
×
437
                }
438
                schedule(s, LOAD_CORE.with("depth", depth).append("load-count", loadCount + 1));
×
439
            } else {
×
440
                // TODO check intro limit
441
                Document introList = new Document()
×
442
                        .append("pubkey", pubkeyHash)
×
443
                        .append("type", INTRO_TYPE_HASH)
×
444
                        .append("status", loading.getValue());
×
445
                if (!has(s, "lists", new Document("pubkey", pubkeyHash).append("type", INTRO_TYPE_HASH))) {
×
446
                    insert(s, "lists", introList);
×
447
                }
448

449
                // No checksum skip in LOAD_CORE: the endorsement extraction logic (below) needs to
450
                // see every nanopub to populate endorsements_loading, which is rebuilt from scratch each UPDATE.
451
                try (var stream = NanopubLoader.retrieveNanopubsFromPeers(INTRO_TYPE_HASH, pubkeyHash)) {
×
452
                    NanopubLoader.loadStreamInParallel(stream, np -> {
×
453
                        try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
454
                            loadNanopub(ws, np, pubkeyHash, INTRO_TYPE);
×
455
                        }
456
                    });
×
457
                }
458

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

461
                // TODO check endorsement limit
462
                Document endorseList = new Document()
×
463
                        .append("pubkey", pubkeyHash)
×
464
                        .append("type", ENDORSE_TYPE_HASH)
×
465
                        .append("status", loading.getValue());
×
466
                if (!has(s, "lists", new Document("pubkey", pubkeyHash).append("type", ENDORSE_TYPE_HASH))) {
×
467
                    insert(s, "lists", endorseList);
×
468
                }
469

470
                try (var stream = NanopubLoader.retrieveNanopubsFromPeers(ENDORSE_TYPE_HASH, pubkeyHash)) {
×
471
                    stream.forEach(m -> {
×
472
                        if (!m.isSuccess())
×
473
                            throw new AbortingTaskException("Failed to download nanopub; aborting task...");
×
474
                        Nanopub nanopub = m.getNanopub();
×
475
                        loadNanopub(s, nanopub, pubkeyHash, ENDORSE_TYPE);
×
476
                        String sourceNpId = TrustyUriUtils.getArtifactCode(nanopub.getUri().stringValue());
×
477
                        Validate.notNull(sourceNpId);
×
478
                        for (Statement st : nanopub.getAssertion()) {
×
479
                            if (!st.getPredicate().equals(Utils.APPROVES_OF)) continue;
×
480
                            if (!(st.getObject() instanceof IRI)) continue;
×
481
                            if (!agentId.equals(st.getSubject().stringValue())) continue;
×
482
                            String objStr = st.getObject().stringValue();
×
483
                            if (!TrustyUriUtils.isPotentialTrustyUri(objStr)) continue;
×
484
                            String endorsedNpId = TrustyUriUtils.getArtifactCode(objStr);
×
485
                            Validate.notNull(endorsedNpId);
×
486
                            Document endorsement = new Document("agent", agentId)
×
487
                                    .append("pubkey", pubkeyHash)
×
488
                                    .append("endorsedNanopub", endorsedNpId)
×
489
                                    .append("source", sourceNpId);
×
490
                            if (!has(s, "endorsements_loading", endorsement)) {
×
491
                                insert(s, "endorsements_loading",
×
492
                                        endorsement.append("status", toRetrieve.getValue()));
×
493
                            }
494
                        }
×
495
                    });
×
496
                }
497

498
                set(s, "lists", endorseList.append("status", loaded.getValue()));
×
499

500
                Document df = new Document("pubkey", pubkeyHash).append("type", "$");
×
501
                if (!has(s, "lists", df)) insert(s, "lists",
×
502
                        df.append("status", encountered.getValue()));
×
503

504
                set(s, "accounts_loading", agentAccount.append("status", visited.getValue()));
×
505

506
                schedule(s, LOAD_CORE.with("depth", depth).append("load-count", loadCount + 1));
×
507
            }
508

509
        }
×
510

511
        // At the end of this step, we have added new endorsement
512
        // links to yet-to-retrieve agent introductions:
513
        // ------------------------------------------------------------
514
        //
515
        //         o      ----endorses----> [intro]
516
        //    --> /#\  /o\___            (to-retrieve)
517
        //        / \  \_/^^^
518
        //         (visited)
519
        //
520
        //    ========[X] trust path
521
        //
522
        // ------------------------------------------------------------
523
        // Only one endorsement is shown here, but there are typically
524
        // several.
525

526
    },
527

528
    FINISH_ITERATION {
33✔
529
        public void run(ClientSession s, Document taskDoc) {
530

531
            int depth = taskDoc.getInteger("depth");
×
532
            int loadCount = taskDoc.getInteger("load-count");
×
533

534
            if (loadCount == 0) {
×
535
                log.info("No new cores loaded; finishing iteration");
×
536
                schedule(s, CALCULATE_TRUST_SCORES);
×
537
            } else if (depth == MAX_TRUST_PATH_DEPTH) {
×
538
                log.info("Maximum depth reached: {}", depth);
×
539
                schedule(s, CALCULATE_TRUST_SCORES);
×
540
            } else {
541
                log.info("Progressing iteration at depth {}", depth + 1);
×
542
                schedule(s, LOAD_DECLARATIONS.with("depth", depth + 1));
×
543
            }
544

545
        }
×
546

547
    },
548

549
    CALCULATE_TRUST_SCORES {
33✔
550

551
        // DB read from: accounts, trustPaths
552
        // DB write to:  accounts
553

554
        public void run(ClientSession s, Document taskDoc) {
555

556
            while (true) {
557
                Document d = getOne(s, "accounts_loading", new Document("status", expanded.getValue()));
×
558
                if (d == null) break;
×
559

560
                double ratio = 0.0;
×
561
                Map<String, Boolean> seenPathElements = new HashMap<>();
×
562
                int pathCount = 0;
×
563
                try (MongoCursor<Document> trustPaths = collection("trustPaths_loading").find(s,
×
564
                        new Document("agent", d.get("agent").toString()).append("pubkey", d.get("pubkey").toString())
×
565
                ).sort(orderBy(ascending("depth"), descending("ratio"), ascending("sorthash"))).cursor()) {
×
566
                    while (trustPaths.hasNext()) {
×
567
                        Document trustPath = trustPaths.next();
×
568
                        ratio += trustPath.getDouble("ratio");
×
569
                        boolean independentPath = true;
×
570
                        String[] pathElements = trustPath.getString("_id").split(" ");
×
571
                        // Iterate over path elements, ignoring first (root) and last (this agent/pubkey):
572
                        for (int i = 1; i < pathElements.length - 1; i++) {
×
573
                            String p = pathElements[i];
×
574
                            if (seenPathElements.containsKey(p)) {
×
575
                                independentPath = false;
×
576
                                break;
×
577
                            }
578
                            seenPathElements.put(p, true);
×
579
                        }
580
                        if (independentPath) pathCount += 1;
×
581
                    }
×
582
                }
583
                double rawQuota = GLOBAL_QUOTA * ratio;
×
584
                int quota = (int) rawQuota;
×
585
                if (rawQuota < MIN_USER_QUOTA) {
×
586
                    quota = MIN_USER_QUOTA;
×
587
                } else if (rawQuota > MAX_USER_QUOTA) {
×
588
                    quota = MAX_USER_QUOTA;
×
589
                }
590
                set(s, "accounts_loading",
×
591
                        d.append("status", processed.getValue())
×
592
                                .append("ratio", ratio)
×
593
                                .append("pathCount", pathCount)
×
594
                                .append("quota", quota)
×
595
                );
596
            }
×
597
            schedule(s, AGGREGATE_AGENTS);
×
598

599
        }
×
600

601
    },
602

603
    AGGREGATE_AGENTS {
33✔
604

605
        // DB read from: accounts, agents
606
        // DB write to:  accounts, agents
607

608
        public void run(ClientSession s, Document taskDoc) {
609

610
            while (true) {
611
                Document a = getOne(s, "accounts_loading", new Document("status", processed.getValue()));
×
612
                if (a == null) break;
×
613

614
                Document agentId = new Document("agent", a.get("agent").toString()).append("status", processed.getValue());
×
615
                int count = 0;
×
616
                int pathCountSum = 0;
×
617
                double totalRatio = 0.0d;
×
618
                try (MongoCursor<Document> agentAccounts = collection("accounts_loading").find(s, agentId).cursor()) {
×
619
                    while (agentAccounts.hasNext()) {
×
620
                        Document d = agentAccounts.next();
×
621
                        count++;
×
622
                        pathCountSum += d.getInteger("pathCount");
×
623
                        totalRatio += d.getDouble("ratio");
×
624
                    }
×
625
                }
626
                collection("accounts_loading").updateMany(s, agentId, new Document("$set",
×
627
                        new DbEntryWrapper(aggregated).getDocument()));
×
628
                insert(s, "agents_loading",
×
629
                        agentId.append("accountCount", count)
×
630
                                .append("avgPathCount", (double) pathCountSum / count)
×
631
                                .append("totalRatio", totalRatio)
×
632
                );
633
            }
×
634
            schedule(s, ASSIGN_PUBKEYS);
×
635

636
        }
×
637

638
    },
639

640
    ASSIGN_PUBKEYS {
33✔
641

642
        // DB read from: accounts
643
        // DB write to:  accounts
644

645
        public void run(ClientSession s, Document taskDoc) {
646

647
            while (true) {
648
                Document a = getOne(s, "accounts_loading", new DbEntryWrapper(aggregated).getDocument());
×
649
                if (a == null) break;
×
650

651
                Document pubkeyId = new Document("pubkey", a.get("pubkey").toString());
×
652
                if (collection("accounts_loading").countDocuments(s, pubkeyId) == 1) {
×
653
                    collection("accounts_loading").updateMany(s, pubkeyId,
×
654
                            new Document("$set", new DbEntryWrapper(approved).getDocument()));
×
655
                } else {
656
                    // TODO At the moment all get marked as 'contested'; implement more nuanced algorithm
657
                    collection("accounts_loading").updateMany(s, pubkeyId, new Document("$set",
×
658
                            new DbEntryWrapper(contested).getDocument()));
×
659
                }
660
            }
×
661
            schedule(s, DETERMINE_UPDATES);
×
662

663
        }
×
664

665
    },
666

667
    DETERMINE_UPDATES {
33✔
668

669
        // DB read from: accounts
670
        // DB write to:  accounts
671

672
        public void run(ClientSession s, Document taskDoc) {
673

674
            // TODO Handle contested accounts properly:
675
            for (Document d : collection("accounts_loading").find(
×
676
                    new DbEntryWrapper(approved).getDocument())) {
×
677
                // TODO Consider quota too:
678
                Document accountId = new Document("agent", d.get("agent").toString()).append("pubkey", d.get("pubkey").toString());
×
679
                if (collection(Collection.ACCOUNTS.toString()) == null || !has(s, Collection.ACCOUNTS.toString(),
×
680
                        accountId.append("status", loaded.getValue()))) {
×
681
                    set(s, "accounts_loading", d.append("status", toLoad.getValue()));
×
682
                } else {
683
                    set(s, "accounts_loading", d.append("status", loaded.getValue()));
×
684
                }
685
            }
×
686
            schedule(s, FINALIZE_TRUST_STATE);
×
687

688
        }
×
689

690
    },
691

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

700
            schedule(s, RELEASE_DATA.with("newTrustStateHash", newTrustStateHash).append("previousTrustStateHash", previousTrustStateHash));
×
701
        }
×
702

703
    },
704

705
    RELEASE_DATA {
33✔
706

707
        private static final int TRUST_STATE_SNAPSHOT_RETENTION = 100;
708

709
        public void run(ClientSession s, Document taskDoc) {
710
            ServerStatus status = getServerStatus(s);
×
711

712
            String newTrustStateHash = taskDoc.get("newTrustStateHash").toString();
×
713
            String previousTrustStateHash = taskDoc.getString("previousTrustStateHash");  // may be null
×
714

715
            // Renaming collections is run outside of a transaction, but is idempotent operation, so can safely be retried if task fails:
716
            rename("accounts_loading", Collection.ACCOUNTS.toString());
×
717
            rename("trustPaths_loading", "trustPaths");
×
718
            rename("agents_loading", Collection.AGENTS.toString());
×
719
            rename("endorsements_loading", "endorsements");
×
720

721
            if (previousTrustStateHash == null || !previousTrustStateHash.equals(newTrustStateHash)) {
×
722
                increaseStateCounter(s);
×
723
                setValue(s, Collection.SERVER_INFO.toString(), "trustStateHash", newTrustStateHash);
×
724
                Object trustStateCounter = getValue(s, Collection.SERVER_INFO.toString(), "trustStateCounter");
×
725
                insert(s, "debug_trustPaths", new Document()
×
726
                        .append("trustStateTxt", DebugPage.getTrustPathsTxt(s))
×
727
                        .append("trustStateHash", newTrustStateHash)
×
728
                        .append("trustStateCounter", trustStateCounter)
×
729
                );
730

731
                // Structured hash-keyed snapshot for consumer mirroring (#107).
732
                // Reads the accounts collection just renamed from accounts_loading above (:697).
733
                List<Document> snapshotAccounts = new ArrayList<>();
×
734
                for (Document a : collection(Collection.ACCOUNTS.toString()).find(s)) {
×
735
                    String pubkey = a.getString("pubkey");
×
736
                    if ("$".equals(pubkey)) continue;
×
737
                    snapshotAccounts.add(new Document()
×
738
                            .append("pubkey", pubkey)
×
739
                            .append("agent", a.getString("agent"))
×
740
                            .append("name", a.getString("name"))
×
741
                            .append("nameCreatedAt", a.get("nameCreatedAt"))
×
742
                            .append("status", a.getString("status"))
×
743
                            .append("depth", a.get("depth"))
×
744
                            .append("pathCount", a.get("pathCount"))
×
745
                            .append("ratio", a.get("ratio"))
×
746
                            .append("quota", a.get("quota")));
×
747
                }
×
748
                Document snapshot = new Document()
×
749
                        .append("_id", newTrustStateHash)
×
750
                        .append("trustStateCounter", trustStateCounter)
×
751
                        .append("createdAt", ZonedDateTime.now().toString())
×
752
                        .append("accounts", snapshotAccounts);
×
753
                collection(Collection.TRUST_STATE_SNAPSHOTS.toString()).replaceOne(
×
754
                        s,
755
                        new Document("_id", newTrustStateHash),
756
                        snapshot,
757
                        new ReplaceOptions().upsert(true));
×
758

759
                // Prune beyond retention: collect _ids of snapshots past the Nth most recent, delete them.
760
                // trustStateCounter is monotonically increasing (see increaseStateCounter above), so ordering is well-defined.
761
                List<Object> toPrune = new ArrayList<>();
×
762
                try (MongoCursor<Document> stale = collection(Collection.TRUST_STATE_SNAPSHOTS.toString())
×
763
                        .find(s)
×
764
                        .sort(descending("trustStateCounter"))
×
765
                        .skip(TRUST_STATE_SNAPSHOT_RETENTION)
×
766
                        .projection(new Document("_id", 1))
×
767
                        .cursor()) {
×
768
                    while (stale.hasNext()) {
×
769
                        toPrune.add(stale.next().get("_id"));
×
770
                    }
771
                }
772
                if (!toPrune.isEmpty()) {
×
773
                    collection(Collection.TRUST_STATE_SNAPSHOTS.toString()).deleteMany(
×
774
                            s, new Document("_id", new Document("$in", toPrune)));
775
                }
776
            }
777

778
            if (status == coreLoading) {
×
779
                setServerStatus(s, coreReady);
×
780
            } else {
781
                setServerStatus(s, ready);
×
782
            }
783

784
            // Run update after 1h:
785
            schedule(s, UPDATE.withDelay(60 * 60 * 1000));
×
786
        }
×
787

788
    },
789

790
    UPDATE {
33✔
791
        public void run(ClientSession s, Document taskDoc) {
792
            ServerStatus status = getServerStatus(s);
×
793
            if (status == ready || status == coreReady) {
×
794
                setServerStatus(s, updating);
×
795
                schedule(s, INIT_COLLECTIONS);
×
796
            } else {
797
                log.info("Postponing update; currently in status {}", status);
×
798
                schedule(s, UPDATE.withDelay(10 * 60 * 1000));
×
799
            }
800

801
        }
×
802

803
    },
804

805
    LOAD_FULL {
33✔
806
        public void run(ClientSession s, Document taskDoc) {
807
            if ("false".equals(System.getenv("REGISTRY_PERFORM_FULL_LOAD"))) return;
15!
808

809
            ServerStatus status = getServerStatus(s);
9✔
810
            if (status != coreReady && status != ready && status != updating) {
27!
811
                log.info("Server currently not ready; checking again later");
9✔
812
                schedule(s, LOAD_FULL.withDelay(1000));
15✔
813
                return;
3✔
814
            }
815

816
            Document a = getOne(s, Collection.ACCOUNTS.toString(), new DbEntryWrapper(toLoad).getDocument());
×
817
            if (a == null) {
×
818
                log.info("Nothing to load");
×
819
                if (status == coreReady) {
×
820
                    log.info("Full load finished");
×
821
                    setServerStatus(s, ready);
×
822
                }
823
                log.info("Scheduling optional loading checks");
×
824
                schedule(s, RUN_OPTIONAL_LOAD.withDelay(100));
×
825
            } else {
826
                final String ph = a.getString("pubkey");
×
827
                boolean quotaReached = false;
×
828
                if (!ph.equals("$")) {
×
829
                    if (!AgentFilter.isAllowed(s, ph)) {
×
830
                        log.info("Skipping pubkey {} (not covered by agent filter)", ph);
×
831
                        set(s, Collection.ACCOUNTS.toString(), a.append("status", skipped.getValue()));
×
832
                        schedule(s, LOAD_FULL.withDelay(100));
×
833
                        return;
×
834
                    }
835
                    if (AgentFilter.isOverQuota(s, ph)) {
×
836
                        log.info("Skipping pubkey {} (quota exceeded)", ph);
×
837
                        quotaReached = true;
×
838
                    } else {
839
                        long startTime = System.nanoTime();
×
840
                        AtomicLong totalLoaded = new AtomicLong(0);
×
841

842
                        // Load per covered type (or "$" if no restriction) with checksum skip-ahead
843
                        for (String typeHash : getLoadTypeHashes(s, ph)) {
×
844
                            String checksums = buildChecksumFallbacks(s, ph, typeHash);
×
845
                            try (var stream = NanopubLoader.retrieveNanopubsFromPeers(typeHash, ph, checksums)) {
×
846
                                NanopubLoader.loadStreamInParallel(stream, np -> {
×
847
                                    if (!CoverageFilter.isCovered(np)) return;
×
848
                                    try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
849
                                        if (!AgentFilter.isOverQuota(ws, ph)) {
×
850
                                            loadNanopub(ws, np, ph, "$");
×
851
                                            totalLoaded.incrementAndGet();
×
852
                                        }
853
                                    }
854
                                });
×
855
                            }
856
                        }
×
857

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

862
                        if (AgentFilter.isOverQuota(s, ph)) {
×
863
                            quotaReached = true;
×
864
                        }
865
                    }
866
                }
867

868
                Document l = getOne(s, "lists", new Document().append("pubkey", ph).append("type", "$"));
×
869
                if (l != null) set(s, "lists", l.append("status", loaded.getValue()));
×
870
                EntryStatus accountStatus = quotaReached ? capped : loaded;
×
871
                int effectiveQuota = AgentFilter.getQuota(s, ph);
×
872
                if (effectiveQuota >= 0) {
×
873
                    a.append("quota", effectiveQuota);
×
874
                }
875
                set(s, Collection.ACCOUNTS.toString(), a.append("status", accountStatus.getValue()));
×
876

877
                schedule(s, LOAD_FULL.withDelay(100));
×
878
            }
879
        }
×
880

881
        @Override
882
        public boolean runAsTransaction() {
883
            // TODO Make this a transaction once we connect to other Nanopub Registry instances:
884
            return false;
×
885
        }
886

887
    },
888

889
    RUN_OPTIONAL_LOAD {
33✔
890

891
        private static final int BATCH_SIZE = Integer.parseInt(
15✔
892
                Utils.getEnv("REGISTRY_OPTIONAL_LOAD_BATCH_SIZE", "100"));
3✔
893

894
        public void run(ClientSession s, Document taskDoc) {
895
            if ("false".equals(System.getenv("REGISTRY_ENABLE_OPTIONAL_LOAD"))) {
×
896
                schedule(s, CHECK_NEW.withDelay(500));
×
897
                return;
×
898
            }
899

900
            AtomicLong totalLoaded = new AtomicLong(0);
×
901

902
            // Phase 1: Process encountered intro lists (core loading)
903
            while (totalLoaded.get() < BATCH_SIZE) {
×
904
                Document di = getOne(s, "lists", new Document("type", INTRO_TYPE_HASH).append("status", encountered.getValue()));
×
905
                if (di == null) break;
×
906

907
                final String pubkeyHash = di.getString("pubkey");
×
908
                Validate.notNull(pubkeyHash);
×
909
                log.info("Optional core loading: {}", pubkeyHash);
×
910

911
                String introChecksums = buildChecksumFallbacks(s, pubkeyHash, INTRO_TYPE_HASH);
×
912
                try (var stream = NanopubLoader.retrieveNanopubsFromPeers(INTRO_TYPE_HASH, pubkeyHash, introChecksums)) {
×
913
                    NanopubLoader.loadStreamInParallel(stream, np -> {
×
914
                        try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
915
                            loadNanopub(ws, np, pubkeyHash, INTRO_TYPE);
×
916
                            totalLoaded.incrementAndGet();
×
917
                        }
918
                    });
×
919
                }
920
                set(s, "lists", di.append("status", loaded.getValue()));
×
921

922
                String endorseChecksums = buildChecksumFallbacks(s, pubkeyHash, ENDORSE_TYPE_HASH);
×
923
                try (var stream = NanopubLoader.retrieveNanopubsFromPeers(ENDORSE_TYPE_HASH, pubkeyHash, endorseChecksums)) {
×
924
                    NanopubLoader.loadStreamInParallel(stream, np -> {
×
925
                        try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
926
                            loadNanopub(ws, np, pubkeyHash, ENDORSE_TYPE);
×
927
                            totalLoaded.incrementAndGet();
×
928
                        }
929
                    });
×
930
                }
931

932
                Document de = new Document("pubkey", pubkeyHash).append("type", ENDORSE_TYPE_HASH);
×
933
                if (has(s, "lists", de)) {
×
934
                    set(s, "lists", de.append("status", loaded.getValue()));
×
935
                } else {
936
                    insert(s, "lists", de.append("status", loaded.getValue()));
×
937
                }
938

939
                Document df = new Document("pubkey", pubkeyHash).append("type", "$");
×
940
                if (!has(s, "lists", df)) insert(s, "lists", df.append("status", encountered.getValue()));
×
941
            }
×
942

943
            // Phase 2: Process encountered full lists (if budget remains)
944
            while (totalLoaded.get() < BATCH_SIZE) {
×
945
                Document df = getOne(s, "lists", new Document("type", "$").append("status", encountered.getValue()));
×
946
                if (df == null) break;
×
947

948
                final String pubkeyHash = df.getString("pubkey");
×
949
                log.info("Optional full loading: {}", pubkeyHash);
×
950

951
                // Load per covered type (or "$" if no restriction) with checksum skip-ahead
952
                for (String typeHash : getLoadTypeHashes(s, pubkeyHash)) {
×
953
                    String checksums = buildChecksumFallbacks(s, pubkeyHash, typeHash);
×
954
                    try (var stream = NanopubLoader.retrieveNanopubsFromPeers(typeHash, pubkeyHash, checksums)) {
×
955
                        NanopubLoader.loadStreamInParallel(stream, np -> {
×
956
                            if (!CoverageFilter.isCovered(np)) return;
×
957
                            try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
958
                                loadNanopub(ws, np, pubkeyHash, "$");
×
959
                                totalLoaded.incrementAndGet();
×
960
                            }
961
                        });
×
962
                    }
963
                }
×
964

965
                set(s, "lists", df.append("status", loaded.getValue()));
×
966

967
                // Backfill nanopubs stored locally during the transitional period (i.e. before
968
                // the $ list was loaded). Such nanopubs were stored in the nanopubs collection by
969
                // simpleLoad() but never added to listEntries; add them to the $ list now.
970
                log.info("Backfilling locally stored nanopubs for pubkey: {}", pubkeyHash);
×
971
                try (MongoCursor<Document> npCursor = collection(Collection.NANOPUBS.toString())
×
972
                        .find(s, new Document("pubkey", pubkeyHash)).cursor()) {
×
973
                    while (npCursor.hasNext()) {
×
974
                        String fullId = npCursor.next().getString("fullId");
×
975
                        if (fullId == null) continue;
×
976
                        try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
977
                            Nanopub np = NanopubLoader.retrieveLocalNanopub(ws, fullId);
×
978
                            if (np != null && CoverageFilter.isCovered(np)) {
×
979
                                loadNanopub(ws, np, pubkeyHash, "$");
×
980
                                totalLoaded.incrementAndGet();
×
981
                            }
982
                        } catch (Exception ex) {
×
983
                            log.info("Error backfilling nanopub {}: {}", fullId, ex.getMessage());
×
984
                        }
×
985
                    }
×
986
                }
987
            }
×
988

989
            if (totalLoaded.get() > 0) {
×
990
                log.info("Optional load batch completed: {} nanopubs across multiple pubkeys", totalLoaded.get());
×
991
            }
992

993
            if (prioritizeAllPubkeys()) {
×
994
                // Check if there are more pubkeys waiting to be processed
995
                boolean moreWork = has(s, "lists", new Document("type", INTRO_TYPE_HASH).append("status", encountered.getValue()))
×
996
                        || has(s, "lists", new Document("type", "$").append("status", encountered.getValue()));
×
997
                if (moreWork) {
×
998
                    // Continue processing without a full CHECK_NEW cycle in between.
999
                    // CHECK_NEW will run naturally once all encountered lists are processed.
1000
                    schedule(s, RUN_OPTIONAL_LOAD.withDelay(10));
×
1001
                } else {
1002
                    schedule(s, CHECK_NEW.withDelay(500));
×
1003
                }
1004
            } else {
×
1005
                // Throttled: yield to CHECK_NEW after each batch to prioritize approved pubkeys
1006
                schedule(s, CHECK_NEW.withDelay(500));
×
1007
            }
1008
        }
×
1009

1010
    },
1011

1012
    CHECK_NEW {
33✔
1013
        public void run(ClientSession s, Document taskDoc) {
1014
            RegistryPeerConnector.checkPeers(s);
×
1015
            // Keep legacy connection during transition period:
1016
            LegacyConnector.checkForNewNanopubs(s);
×
1017
            // TODO Somehow throttle the loading of such potentially non-approved nanopubs
1018

1019
            schedule(s, LOAD_FULL.withDelay(100));
×
1020
        }
×
1021

1022
        @Override
1023
        public boolean runAsTransaction() {
1024
            // Peer sync includes long-running streaming fetches that would exceed
1025
            // MongoDB's transaction timeout; each operation is individually safe.
1026
            return false;
×
1027
        }
1028

1029
    };
1030

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

1033
    public abstract void run(ClientSession s, Document taskDoc) throws Exception;
1034

1035
    public boolean runAsTransaction() {
1036
        return true;
×
1037
    }
1038

1039
    Document asDocument() {
1040
        return withDelay(0L);
12✔
1041
    }
1042

1043
    private Document withDelay(long delay) {
1044
        // TODO Rename "not-before" to "notBefore" for consistency with other field names
1045
        return new Document()
15✔
1046
                .append("not-before", System.currentTimeMillis() + delay)
21✔
1047
                .append("action", name());
6✔
1048
    }
1049

1050
    private Document with(String key, Object value) {
1051
        return asDocument().append(key, value);
×
1052
    }
1053

1054
    private static boolean prioritizeAllPubkeys() {
1055
        return "true".equals(System.getenv("REGISTRY_PRIORITIZE_ALL_PUBKEYS"));
×
1056
    }
1057

1058
    /**
1059
     * Returns the type hashes to load for a given pubkey. When coverage is unrestricted,
1060
     * returns just "$" (all types in one request). When restricted, returns each covered
1061
     * type hash for per-type fetching with checksum skip-ahead.
1062
     *
1063
     * TODO: Fetching "$" from peers with type restrictions will only return their covered
1064
     * types, not all types. To get full coverage, we'd need to fetch per-type from such peers.
1065
     * Additionally, checksum-based skip-ahead won't work correctly against such peers, because
1066
     * their "$" list has different checksums due to the differing type subset. This means full
1067
     * re-downloads on every cycle. Per-type fetching would solve both issues.
1068
     */
1069
    private static java.util.List<String> getLoadTypeHashes(ClientSession s, String pubkeyHash) {
1070
        if (CoverageFilter.coversAllTypes()) {
×
1071
            return java.util.List.of("$");
×
1072
        }
1073
        return java.util.List.copyOf(CoverageFilter.getCoveredTypeHashes());
×
1074
    }
1075

1076
    // TODO Move these to setting:
1077
    private static final int MAX_TRUST_PATH_DEPTH = 10;
1078
    private static final double MIN_TRUST_PATH_RATIO = 0.00000001;
1079
    //private static final double MIN_TRUST_PATH_RATIO = 0.01; // For testing
1080
    private static final int GLOBAL_QUOTA = Integer.parseInt(
12✔
1081
            Utils.getEnv("REGISTRY_GLOBAL_QUOTA", "1000000000"));
3✔
1082
    private static final int MIN_USER_QUOTA = Integer.parseInt(
12✔
1083
            Utils.getEnv("REGISTRY_MIN_USER_QUOTA", "1000"));
3✔
1084
    private static final int MAX_USER_QUOTA = Integer.parseInt(
12✔
1085
            Utils.getEnv("REGISTRY_MAX_USER_QUOTA", "100000"));
3✔
1086

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

1089
    private static volatile String currentTaskName;
1090
    private static volatile long currentTaskStartTime;
1091

1092
    public static String getCurrentTaskName() {
1093
        return currentTaskName;
×
1094
    }
1095

1096
    public static long getCurrentTaskStartTime() {
1097
        return currentTaskStartTime;
×
1098
    }
1099

1100
    /**
1101
     * The super important base entry point!
1102
     */
1103
    static void runTasks() {
1104
        try (ClientSession s = RegistryDB.getClient().startSession()) {
×
1105
            if (!RegistryDB.isInitialized(s)) {
×
1106
                schedule(s, INIT_DB); // does not yet execute, only schedules
×
1107
            }
1108

1109
            while (true) {
1110
                FindIterable<Document> taskResult = tasksCollection.find(s).sort(ascending("not-before"));
×
1111
                Document taskDoc = taskResult.first();
×
1112
                long sleepTime = 10;
×
1113
                if (taskDoc != null && taskDoc.getLong("not-before") < System.currentTimeMillis()) {
×
1114
                    Task task = valueOf(taskDoc.getString("action"));
×
1115
                    log.info("Running task: {}", task.name());
×
1116
                    if (task.runAsTransaction()) {
×
1117
                        try {
1118
                            s.startTransaction();
×
1119
                            log.info("Transaction started");
×
1120
                            runTask(task, taskDoc);
×
1121
                            s.commitTransaction();
×
1122
                            log.info("Transaction committed");
×
1123
                        } catch (Exception ex) {
×
1124
                            log.info("Aborting transaction", ex);
×
1125
                            abortTransaction(s, ex.getMessage());
×
1126
                            log.info("Transaction aborted");
×
1127
                            sleepTime = 1000;
×
1128
                        } finally {
1129
                            cleanTransactionWithRetry(s);
×
1130
                        }
×
1131
                    } else {
1132
                        try {
1133
                            runTask(task, taskDoc);
×
1134
                        } catch (Exception ex) {
×
1135
                            log.info("Transaction failed", ex);
×
1136
                        }
×
1137
                    }
1138
                }
1139
                try {
1140
                    Thread.sleep(sleepTime);
×
1141
                } catch (InterruptedException ex) {
×
1142
                    // ignore
1143
                }
×
1144
            }
×
1145
        }
1146
    }
1147

1148
    static void runTask(Task task, Document taskDoc) throws Exception {
1149
        try (ClientSession s = RegistryDB.getClient().startSession()) {
9✔
1150
            log.info("Executing task: {}", task.name());
15✔
1151
            currentTaskName = task.name();
9✔
1152
            currentTaskStartTime = System.currentTimeMillis();
6✔
1153
            task.run(s, taskDoc);
12✔
1154
            tasksCollection.deleteOne(s, eq("_id", taskDoc.get("_id")));
27✔
1155
            log.info("Task {} completed and removed from queue.", task.name());
15✔
1156
        } finally {
1157
            currentTaskName = null;
6✔
1158
        }
1159
    }
3✔
1160

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

1180
    public synchronized static void cleanTransactionWithRetry(ClientSession mongoSession) {
1181
        boolean successful = false;
×
1182
        while (!successful) {
×
1183
            try {
1184
                if (mongoSession.hasActiveTransaction()) {
×
1185
                    mongoSession.abortTransaction();
×
1186
                }
1187
                successful = true;
×
1188
            } catch (Exception ex) {
×
1189
                log.info("Cleaning transaction failed. ", ex);
×
1190
                try {
1191
                    Thread.sleep(1000);
×
1192
                } catch (InterruptedException iex) {
×
1193
                    // ignore
1194
                }
×
1195
            }
×
1196
        }
1197
    }
×
1198

1199
    private static IntroNanopub getAgentIntro(ClientSession mongoSession, String nanopubId) {
1200
        IntroNanopub agentIntro = new IntroNanopub(NanopubLoader.retrieveNanopub(mongoSession, nanopubId));
×
1201
        if (agentIntro.getUser() == null) return null;
×
1202
        loadNanopub(mongoSession, agentIntro.getNanopub());
×
1203
        return agentIntro;
×
1204
    }
1205

1206

1207
    private static void setServerStatus(ClientSession mongoSession, ServerStatus status) {
1208
        setValue(mongoSession, Collection.SERVER_INFO.toString(), "status", status.toString());
21✔
1209
    }
3✔
1210

1211
    private static ServerStatus getServerStatus(ClientSession mongoSession) {
1212
        Object status = getValue(mongoSession, Collection.SERVER_INFO.toString(), "status");
18✔
1213
        if (status == null) {
6!
1214
            throw new RuntimeException("Illegal DB state: serverInfo status unavailable");
×
1215
        }
1216
        return ServerStatus.valueOf(status.toString());
12✔
1217
    }
1218

1219
    private static void schedule(ClientSession mongoSession, Task task) {
1220
        schedule(mongoSession, task.asDocument());
12✔
1221
    }
3✔
1222

1223
    private static void schedule(ClientSession mongoSession, Document taskDoc) {
1224
        log.info("Scheduling task: {}", taskDoc.getString("action"));
18✔
1225
        tasksCollection.insertOne(mongoSession, taskDoc);
12✔
1226
    }
3✔
1227

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