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

knowledgepixels / nanopub-registry / 28155387420

25 Jun 2026 07:53AM UTC coverage: 31.926% (-0.2%) from 32.089%
28155387420

push

github

web-flow
chore: enhance and standardize logging across multiple components (#116)

* chore(EntryStatus): enhance logging for null and unsupported status value handling

* chore(logging): standardize logger variable names across multiple classes

* chore(CoverageFilter): enhance logging for coverage filter initialization and type checks

* chore(RegistryPeerConnector): enhance logging for peer connection and nanopub fetching

* chore(logging): enhance logging for request handling and error reporting in multiple pages

* chore(MainVerticle): enhance logging for HTTP server startup, request routing, and POST processing

* chore(Task): improve logging messages

* chore(Task): enhance logging for server status checks and account loading processes

* chore(RegistryInfo): add logging messages for RegistryInfo snapshot assembly and JSON serialization

* chore(logging): enhance logging throughout various components for better traceability and debugging

* chore(Utils): enhance logging for user IRI extraction in IntroNanopub

* chore(TrustStatePage): enhance logging for trust-state snapshot resolution and querying

* chore(NanopubLoader): enhance logging for nanopub retrieval and processing

* chore(Task): enhance logging for task execution and status transitions

313 of 1106 branches covered (28.3%)

Branch coverage included in aggregate %.

1048 of 3157 relevant lines covered (33.2%)

5.51 hits per line

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

11.84
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
            logger.info("Running INIT_DB task: initializing a fresh database");
9✔
41
            setServerStatus(s, launching);
9✔
42

43
            increaseStateCounter(s);
6✔
44
            if (RegistryDB.isInitialized(s)) {
9!
45
                logger.error("INIT_DB aborted: database is already initialized");
×
46
                throw new RuntimeException("DB already initialized");
×
47
            }
48

49
            long setupId = Math.abs(Utils.getRandom().nextLong());
12✔
50
            boolean testInstance = "true".equals(System.getenv("REGISTRY_TEST_INSTANCE"));
15✔
51
            logger.info("Initializing new database with setupId={} (testInstance={})", setupId, testInstance);
21✔
52

53
            setValue(s, Collection.SERVER_INFO.toString(), "setupId", setupId);
21✔
54
            setValue(s, Collection.SERVER_INFO.toString(), "testInstance", testInstance);
21✔
55

56
            logger.debug("INIT_DB complete; scheduling LOAD_CONFIG task");
9✔
57
            schedule(s, LOAD_CONFIG);
9✔
58
        }
3✔
59

60
    },
61

62
    LOAD_CONFIG {
33✔
63
        public void run(ClientSession s, Document taskDoc) {
64
            logger.info("Running LOAD_CONFIG task");
9✔
65
            ServerStatus status = getServerStatus(s);
9✔
66
            if (status != launching) {
9!
67
                logger.error("LOAD_CONFIG aborted: expected server status '{}' but found '{}'", launching, status);
×
68
                throw new IllegalTaskStatusException("Illegal status for this task: " + status);
×
69
            }
70

71
            String coverageTypes = System.getenv("REGISTRY_COVERAGE_TYPES");
9✔
72
            if (coverageTypes != null) {
6!
73
                logger.info("Setting coverageTypes from REGISTRY_COVERAGE_TYPES: {}", coverageTypes);
×
74
                setValue(s, Collection.SERVER_INFO.toString(), "coverageTypes", coverageTypes);
×
75
            } else {
76
                logger.debug("REGISTRY_COVERAGE_TYPES not set; leaving coverageTypes unset");
9✔
77
            }
78

79
            String coverageAgents = System.getenv("REGISTRY_COVERAGE_AGENTS");
9✔
80
            if (coverageAgents != null) {
6!
81
                logger.info("Setting coverageAgents from REGISTRY_COVERAGE_AGENTS: {}", coverageAgents);
×
82
                setValue(s, Collection.SERVER_INFO.toString(), "coverageAgents", coverageAgents);
×
83
            } else {
84
                logger.debug("REGISTRY_COVERAGE_AGENTS not set; leaving coverageAgents unset");
9✔
85
            }
86

87
            logger.debug("LOAD_CONFIG complete; scheduling LOAD_SETTING task");
9✔
88
            schedule(s, LOAD_SETTING);
9✔
89
        }
3✔
90

91
    },
92

93
    LOAD_SETTING {
33✔
94
        public void run(ClientSession s, Document taskDoc) throws Exception {
95
            logger.info("Running LOAD_SETTING task");
9✔
96
            ServerStatus status = getServerStatus(s);
9✔
97
            if (status != launching) {
9!
98
                logger.error("LOAD_SETTING aborted: expected server status '{}' but found '{}'", launching, status);
×
99
                throw new IllegalTaskStatusException("Illegal status for this task: " + status);
×
100
            }
101

102
            NanopubSetting settingNp = Utils.getSetting();
6✔
103
            String settingId = TrustyUriUtils.getArtifactCode(settingNp.getNanopub().getUri().stringValue());
18✔
104
            logger.info("Loading setting nanopub {}", settingId);
12✔
105
            setValue(s, Collection.SETTING.toString(), "original", settingId);
18✔
106
            setValue(s, Collection.SETTING.toString(), "current", settingId);
18✔
107
            loadNanopub(s, settingNp.getNanopub());
15✔
108

109
            List<Document> bootstrapServices = new ArrayList<>();
12✔
110
            for (IRI i : settingNp.getBootstrapServices()) {
33✔
111
                bootstrapServices.add(new Document("_id", i.stringValue()));
27✔
112
            }
3✔
113
            logger.info("Setting {} bootstrap service(s) from the setting nanopub: {}", bootstrapServices.size(), bootstrapServices);
21✔
114
            // potentially currently hardcoded in the nanopub lib
115
            setValue(s, Collection.SETTING.toString(), "bootstrap-services", bootstrapServices);
18✔
116

117
            boolean performFullLoad = !"false".equals(System.getenv("REGISTRY_PERFORM_FULL_LOAD"));
24!
118
            if (performFullLoad) {
6!
119
                logger.debug("REGISTRY_PERFORM_FULL_LOAD not disabled; scheduling LOAD_FULL task");
9✔
120
                schedule(s, LOAD_FULL);
12✔
121
            } else {
122
                logger.info("REGISTRY_PERFORM_FULL_LOAD=false; skipping LOAD_FULL task");
×
123
            }
124

125
            logger.debug("LOAD_SETTING complete; transitioning server status to '{}' and scheduling INIT_COLLECTIONS", coreLoading);
12✔
126
            setServerStatus(s, coreLoading);
9✔
127
            schedule(s, INIT_COLLECTIONS);
9✔
128
        }
3✔
129
    },
130

131
    INIT_COLLECTIONS {
33✔
132

133
        // DB read from:
134
        // DB write to:  trustPaths, endorsements, accounts
135
        // This state is periodically executed
136

137
        public void run(ClientSession s, Document taskDoc) throws Exception {
138
            logger.info("Running INIT_COLLECTIONS task");
×
139
            ServerStatus status = getServerStatus(s);
×
140
            if (status != coreLoading && status != updating) {
×
141
                logger.error("INIT_COLLECTIONS aborted: expected server status 'coreLoading' or 'updating' but found '{}'", status);
×
142
                throw new IllegalTaskStatusException("Illegal status for this task: " + status);
×
143
            }
144

145
            IndexInitializer.initLoadingCollections(s);
×
146

147
            if ("false".equals(System.getenv("REGISTRY_ENABLE_TRUST_CALCULATION"))) {
×
148
                logger.info("Trust calculation disabled (REGISTRY_ENABLE_TRUST_CALCULATION=false); skipping to FINALIZE_TRUST_STATE");
×
149
                for (Map.Entry<String, Integer> entry : AgentFilter.getExplicitPubkeys().entrySet()) {
×
150
                    String pubkeyHash = entry.getKey();
×
151
                    int quota = entry.getValue();
×
152
                    Document account = new Document("agent", "")
×
153
                            .append("pubkey", pubkeyHash)
×
154
                            .append("status", toLoad.getValue())
×
155
                            .append("depth", 0)
×
156
                            .append("quota", quota);
×
157
                    if (!has(s, "accounts_loading", new Document("pubkey", pubkeyHash))) {
×
158
                        insert(s, "accounts_loading", account);
×
159
                        logger.debug("Seeded explicit pubkey as account: {} (quota={})", pubkeyHash, quota);
×
160
                    }
161
                }
×
162
                schedule(s, FINALIZE_TRUST_STATE);
×
163
                return;
×
164
            }
165

166
            logger.debug("Inserting root trust path entry for base agent");
×
167
            // since this may take long, we start with postfix "_loading"
168
            // and only at completion it's changed to trustPath, endorsements, accounts
169
            insert(s, "trustPaths_loading",
×
170
                    new Document("_id", "$")
171
                            .append("sorthash", "")
×
172
                            .append("agent", "$")
×
173
                            .append("pubkey", "$")
×
174
                            .append("depth", 0)
×
175
                            .append("ratio", 1.0d)
×
176
                            .append("type", "extended")
×
177
            );
178

179
            String agentIntroCollectionUri = Utils.getSetting().getAgentIntroCollection().stringValue();
×
180
            logger.info("Retrieving base agent intro collection: {}", agentIntroCollectionUri);
×
181
            NanopubIndex agentIndex = IndexUtils.castToIndex(NanopubLoader.retrieveNanopub(s, agentIntroCollectionUri));
×
182
            loadNanopub(s, agentIndex);
×
183
            for (IRI el : agentIndex.getElements()) {
×
184
                String declarationAc = TrustyUriUtils.getArtifactCode(el.stringValue());
×
185
                Validate.notNull(declarationAc);
×
186

187
                insert(s, "endorsements_loading",
×
188
                        new Document("agent", "$")
189
                                .append("pubkey", "$")
×
190
                                .append("endorsedNanopub", declarationAc)
×
191
                                .append("source", getValue(s, Collection.SETTING.toString(), "current").toString())
×
192
                                .append("status", toRetrieve.getValue())
×
193

194
                );
195

196
            }
×
197
            insert(s, "accounts_loading",
×
198
                    new Document("agent", "$")
199
                            .append("pubkey", "$")
×
200
                            .append("status", visited.getValue())
×
201
                            .append("depth", 0)
×
202
            );
203

204
            logger.info("Starting iteration at depth 0");
×
205
            schedule(s, LOAD_DECLARATIONS.with("depth", 1));
×
206
        }
×
207

208
        // At the end of this task, the base agent is initialized:
209
        // ------------------------------------------------------------
210
        //
211
        //              $$$$ ----endorses----> [intro]
212
        //              base                (to-retrieve)
213
        //              $$$$
214
        //            (visited)
215
        //
216
        //              [0] trust path
217
        //
218
        // ------------------------------------------------------------
219
        // Only one endorses-link to an introduction is shown here,
220
        // but there are typically several.
221

222
    },
223

224
    LOAD_DECLARATIONS {
33✔
225

226
        // In general, we have at this point accounts with
227
        // endorsement links to unvisited agent introductions:
228
        // ------------------------------------------------------------
229
        //
230
        //         o      ----endorses----> [intro]
231
        //    --> /#\  /o\___            (to-retrieve)
232
        //        / \  \_/^^^
233
        //         (visited)
234
        //
235
        //    ========[X] trust path
236
        //
237
        // ------------------------------------------------------------
238

239
        // DB read from: endorsements, trustEdges, accounts
240
        // DB write to:  endorsements, trustEdges, accounts
241

242
        public void run(ClientSession s, Document taskDoc) {
243

244
            int depth = taskDoc.getInteger("depth");
×
245
            logger.info("Running LOAD_DECLARATIONS task at depth {}", depth);
×
246

247
            while (true) {
248
                Document d = getOne(s, "endorsements_loading",
×
249
                        new DbEntryWrapper(toRetrieve).getDocument());
×
250
                if (d == null) {
×
251
                    break;
×
252
                }
253

254
                IntroNanopub agentIntro = getAgentIntro(s, d.getString("endorsedNanopub"));
×
255
                if (agentIntro != null) {
×
256
                    String agentId = agentIntro.getUser().stringValue();
×
257
                    // foaf:name + dct:created of the intro nanopub. Same name applies to every
258
                    // KeyDeclaration in the intro, so resolve once outside the inner loop.
259
                    String introName = Utils.extractIntroName(agentIntro);
×
260
                    Calendar introCreatedCal = SimpleTimestampPattern.getCreationTime(agentIntro.getNanopub());
×
261
                    Date introCreatedAt = (introCreatedCal == null) ? null : introCreatedCal.getTime();
×
262

263
                    for (KeyDeclaration kd : agentIntro.getKeyDeclarations()) {
×
264
                        String sourceAgent = d.getString("agent");
×
265
                        Validate.notNull(sourceAgent);
×
266
                        String sourcePubkey = d.getString("pubkey");
×
267
                        Validate.notNull(sourcePubkey);
×
268
                        String sourceAc = d.getString("source");
×
269
                        Validate.notNull(sourceAc);
×
270
                        String agentPubkey = Utils.getHash(kd.getPublicKeyString());
×
271
                        Validate.notNull(agentPubkey);
×
272
                        Document trustEdge = new Document("fromAgent", sourceAgent)
×
273
                                .append("fromPubkey", sourcePubkey)
×
274
                                .append("toAgent", agentId)
×
275
                                .append("toPubkey", agentPubkey)
×
276
                                .append("source", sourceAc);
×
277
                        if (!has(s, "trustEdges", trustEdge)) {
×
278
                            boolean invalidated = has(s, "invalidations", new Document("invalidatedNp", sourceAc).append("invalidatingPubkey", sourcePubkey));
×
279
                            if (invalidated) {
×
280
                                logger.info("Trust edge from {}/{} to {}/{} is invalidated by source {}", sourceAgent, sourcePubkey, agentId, agentPubkey, sourceAc);
×
281
                            }
282
                            insert(s, "trustEdges", trustEdge.append("invalidated", invalidated));
×
283
                        }
284

285
                        Document agent = new Document("agent", agentId).append("pubkey", agentPubkey);
×
286
                        Document existing = collection("accounts_loading").find(s, agent).first();
×
287
                        if (existing == null) {
×
288
                            insert(s, "accounts_loading", agent
×
289
                                    .append("status", seen.getValue())
×
290
                                    .append("depth", depth)
×
291
                                    .append("name", introName)
×
292
                                    .append("nameCreatedAt", introCreatedAt));
×
293
                        } else if (introName != null) {
×
294
                            // Per-(agent, pubkey) name policy: keep the name from the intro
295
                            // with the latest dct:created. First write wins when no current
296
                            // timestamp exists; otherwise compare and replace iff strictly newer.
297
                            Date currentCreatedAt = existing.getDate("nameCreatedAt");
×
298
                            if (currentCreatedAt == null
×
299
                                || (introCreatedAt != null && introCreatedAt.after(currentCreatedAt))) {
×
300
                                set(s, "accounts_loading", existing
×
301
                                        .append("name", introName)
×
302
                                        .append("nameCreatedAt", introCreatedAt));
×
303
                            }
304
                        }
305
                    }
×
306

307
                    set(s, "endorsements_loading", d.append("status", retrieved.getValue()));
×
308
                } else {
×
309
                    logger.debug("Discarding endorsement {}: referenced nanopub {} is not a valid agent intro", d.get("_id"), d.getString("endorsedNanopub"));
×
310
                    set(s, "endorsements_loading", d.append("status", discarded.getValue()));
×
311
                }
312
            }
×
313
            logger.info("LOAD_DECLARATIONS at depth {} complete.", depth);
×
314
            schedule(s, EXPAND_TRUST_PATHS.with("depth", depth));
×
315
        }
×
316

317
        // At the end of this step, the key declarations in the agent
318
        // introductions are loaded and the corresponding trust edges
319
        // established:
320
        // ------------------------------------------------------------
321
        //
322
        //        o      ----endorses----> [intro]
323
        //   --> /#\  /o\___                o
324
        //       / \  \_/^^^ ---trusts---> /#\  /o\___
325
        //        (visited)                / \  \_/^^^
326
        //                                   (seen)
327
        //
328
        //   ========[X] trust path
329
        //
330
        // ------------------------------------------------------------
331
        // Only one trust edge per introduction is shown here, but
332
        // there can be several.
333

334
    },
335

336
    EXPAND_TRUST_PATHS {
33✔
337

338
        // DB read from: accounts, trustPaths, trustEdges
339
        // DB write to:  accounts, trustPaths
340

341
        public void run(ClientSession s, Document taskDoc) {
342

343
            int depth = taskDoc.getInteger("depth");
×
344
            logger.info("Running EXPAND_TRUST_PATHS task at depth {}", depth);
×
345

346
            while (true) {
347
                Document d = getOne(s, "accounts_loading",
×
348
                        new Document("status", visited.getValue())
×
349
                                .append("depth", depth - 1)
×
350
                );
351
                if (d == null) {
×
352
                    break;
×
353
                }
354

355
                String agentId = d.getString("agent");
×
356
                Validate.notNull(agentId);
×
357
                String pubkeyHash = d.getString("pubkey");
×
358
                Validate.notNull(pubkeyHash);
×
359

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

364
                if (trustPath == null) {
×
365
                    // Check it again in next iteration:
366
                    set(s, "accounts_loading", d.append("depth", depth));
×
367
                } else {
368
                    // Only first matching trust path is considered
369

370
                    Map<String, Document> newPaths = new HashMap<>();
×
371
                    Map<String, Set<String>> pubkeySets = new HashMap<>();
×
372
                    String currentSetting = getValue(s, Collection.SETTING.toString(), "current").toString();
×
373

374
                    try (MongoCursor<Document> edgeCursor = get(s, "trustEdges",
×
375
                            new Document("fromAgent", agentId)
376
                                    .append("fromPubkey", pubkeyHash)
×
377
                                    .append("invalidated", false)
×
378
                    )) {
379
                        while (edgeCursor.hasNext()) {
×
380
                            Document e = edgeCursor.next();
×
381

382
                            String agent = e.getString("toAgent");
×
383
                            Validate.notNull(agent);
×
384
                            String pubkey = e.getString("toPubkey");
×
385
                            Validate.notNull(pubkey);
×
386
                            String pathId = trustPath.getString("_id") + " " + agent + "|" + pubkey;
×
387
                            newPaths.put(pathId,
×
388
                                    new Document("_id", pathId)
389
                                            .append("sorthash", Utils.getHash(currentSetting + " " + pathId))
×
390
                                            .append("agent", agent)
×
391
                                            .append("pubkey", pubkey)
×
392
                                            .append("depth", depth)
×
393
                                            .append("type", "extended")
×
394
                            );
395
                            if (!pubkeySets.containsKey(agent)) {
×
396
                                pubkeySets.put(agent, new HashSet<>());
×
397
                            }
398
                            pubkeySets.get(agent).add(pubkey);
×
399
                        }
×
400
                    }
401
                    for (String pathId : newPaths.keySet()) {
×
402
                        Document pd = newPaths.get(pathId);
×
403
                        // first divide by agents; then for each agent, divide by number of pubkeys:
404
                        double newRatio = (trustPath.getDouble("ratio") * 0.9) / pubkeySets.size() / pubkeySets.get(pd.getString("agent")).size();
×
405
                        insert(s, "trustPaths_loading", pd.append("ratio", newRatio));
×
406
                    }
×
407
                    // Retain only 10% of the ratio — the other 90% was distributed to children
408
                    double retainedRatio = trustPath.getDouble("ratio") * 0.1;
×
409
                    set(s, "trustPaths_loading", trustPath.append("type", "primary").append("ratio", retainedRatio));
×
410
                    set(s, "accounts_loading", d.append("status", expanded.getValue()));
×
411
                }
412
            }
×
413
            logger.info("EXPAND_TRUST_PATHS at depth {} complete.", depth);
×
414
            schedule(s, LOAD_CORE.with("depth", depth).append("load-count", 0));
×
415
        }
×
416

417
        // At the end of this step, trust paths are updated to include
418
        // the new accounts:
419
        // ------------------------------------------------------------
420
        //
421
        //         o      ----endorses----> [intro]
422
        //    --> /#\  /o\___                o
423
        //        / \  \_/^^^ ---trusts---> /#\  /o\___
424
        //        (expanded)                / \  \_/^^^
425
        //                                    (seen)
426
        //
427
        //    ========[X]=====================[X+1] trust path
428
        //
429
        // ------------------------------------------------------------
430
        // Only one trust path is shown here, but they branch out if
431
        // several trust edges are present.
432

433
    },
434

435
    LOAD_CORE {
33✔
436

437
        // From here on, we refocus on the head of the trust paths:
438
        // ------------------------------------------------------------
439
        //
440
        //         o
441
        //    --> /#\  /o\___
442
        //        / \  \_/^^^
443
        //          (seen)
444
        //
445
        //    ========[X] trust path
446
        //
447
        // ------------------------------------------------------------
448

449
        // DB read from: accounts, trustPaths, endorsements, lists
450
        // DB write to:  accounts, endorsements, lists
451

452
        public void run(ClientSession s, Document taskDoc) {
453

454
            int depth = taskDoc.getInteger("depth");
×
455
            int loadCount = taskDoc.getInteger("load-count");
×
456

457
            Document agentAccount = getOne(s, "accounts_loading",
×
458
                    new Document("depth", depth).append("status", seen.getValue()));
×
459
            final String agentId;
460
            final String pubkeyHash;
461
            final Document trustPath;
462
            if (agentAccount != null) {
×
463
                agentId = agentAccount.getString("agent");
×
464
                Validate.notNull(agentId);
×
465
                pubkeyHash = agentAccount.getString("pubkey");
×
466
                Validate.notNull(pubkeyHash);
×
467
                trustPath = getOne(s, "trustPaths_loading",
×
468
                        new Document("depth", depth)
×
469
                                .append("agent", agentId)
×
470
                                .append("pubkey", pubkeyHash)
×
471
                );
472
            } else {
473
                agentId = null;
×
474
                pubkeyHash = null;
×
475
                trustPath = null;
×
476
            }
477

478
            if (agentAccount == null) {
×
479
                logger.info("LOAD_CORE at depth {} complete: {} account(s) processed", depth, loadCount);
×
480
                schedule(s, FINISH_ITERATION.with("depth", depth).append("load-count", loadCount));
×
481
            } else if (trustPath == null) {
×
482
                logger.debug("Account {}/{} has no trust path at depth {}; marking skipped", agentId, pubkeyHash, depth);
×
483
                // Account was seen but has no trust path at this depth; skip it
484
                set(s, "accounts_loading", agentAccount.append("status", skipped.getValue()));
×
485
                schedule(s, LOAD_CORE.with("depth", depth).append("load-count", loadCount));
×
486
            } else if (trustPath.getDouble("ratio") < MIN_TRUST_PATH_RATIO) {
×
487
                logger.debug("Pubkey {}: trust path ratio {} below minimum {}; skipping core load, marking encountered", pubkeyHash, trustPath.getDouble("ratio"), MIN_TRUST_PATH_RATIO);
×
488
                set(s, "accounts_loading", agentAccount.append("status", skipped.getValue()));
×
489
                Document d = new Document("pubkey", pubkeyHash).append("type", INTRO_TYPE_HASH);
×
490
                if (!has(s, "lists", d)) {
×
491
                    insert(s, "lists", d.append("status", encountered.getValue()));
×
492
                }
493
                schedule(s, LOAD_CORE.with("depth", depth).append("load-count", loadCount + 1));
×
494
            } else {
×
495
                logger.info("Pubkey {}: loading core (intro + endorsements) at depth {}", pubkeyHash, depth);
×
496
                // TODO check intro limit
497
                Document introList = new Document()
×
498
                        .append("pubkey", pubkeyHash)
×
499
                        .append("type", INTRO_TYPE_HASH)
×
500
                        .append("status", loading.getValue());
×
501
                if (!has(s, "lists", new Document("pubkey", pubkeyHash).append("type", INTRO_TYPE_HASH))) {
×
502
                    insert(s, "lists", introList);
×
503
                }
504

505
                // No checksum skip in LOAD_CORE: the endorsement extraction logic (below) needs to
506
                // see every nanopub to populate endorsements_loading, which is rebuilt from scratch each UPDATE.
507
                try (var stream = NanopubLoader.retrieveNanopubsFromPeers(INTRO_TYPE_HASH, pubkeyHash)) {
×
508
                    NanopubLoader.loadStreamInParallel(stream, np -> {
×
509
                        try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
510
                            loadNanopub(ws, np, pubkeyHash, INTRO_TYPE);
×
511
                        }
512
                    });
×
513
                }
514

515
                set(s, "lists", introList.append("status", loaded.getValue()));
×
516
                logger.debug("Pubkey {}: intro list loaded", pubkeyHash);
×
517

518
                // TODO check endorsement limit
519
                Document endorseList = new Document()
×
520
                        .append("pubkey", pubkeyHash)
×
521
                        .append("type", ENDORSE_TYPE_HASH)
×
522
                        .append("status", loading.getValue());
×
523
                if (!has(s, "lists", new Document("pubkey", pubkeyHash).append("type", ENDORSE_TYPE_HASH))) {
×
524
                    insert(s, "lists", endorseList);
×
525
                }
526

527
                try (var stream = NanopubLoader.retrieveNanopubsFromPeers(ENDORSE_TYPE_HASH, pubkeyHash)) {
×
528
                    stream.forEach(m -> {
×
529
                        if (!m.isSuccess()) {
×
530
                            logger.error("Pubkey {}: failed to download an endorsement nanopub; aborting LOAD_CORE task", pubkeyHash);
×
531
                            throw new AbortingTaskException("Failed to download nanopub; aborting task...");
×
532
                        }
533
                        Nanopub nanopub = m.getNanopub();
×
534
                        loadNanopub(s, nanopub, pubkeyHash, ENDORSE_TYPE);
×
535
                        String sourceNpId = TrustyUriUtils.getArtifactCode(nanopub.getUri().stringValue());
×
536
                        Validate.notNull(sourceNpId);
×
537
                        for (Statement st : nanopub.getAssertion()) {
×
538
                            if (!st.getPredicate().equals(Utils.APPROVES_OF)) {
×
539
                                continue;
×
540
                            }
541
                            if (!(st.getObject() instanceof IRI)) {
×
542
                                continue;
×
543
                            }
544
                            if (!agentId.equals(st.getSubject().stringValue())) {
×
545
                                continue;
×
546
                            }
547
                            String objStr = st.getObject().stringValue();
×
548
                            if (!TrustyUriUtils.isPotentialTrustyUri(objStr)) {
×
549
                                continue;
×
550
                            }
551
                            String endorsedNpId = TrustyUriUtils.getArtifactCode(objStr);
×
552
                            Validate.notNull(endorsedNpId);
×
553
                            Document endorsement = new Document("agent", agentId)
×
554
                                    .append("pubkey", pubkeyHash)
×
555
                                    .append("endorsedNanopub", endorsedNpId)
×
556
                                    .append("source", sourceNpId);
×
557
                            if (!has(s, "endorsements_loading", endorsement)) {
×
558
                                insert(s, "endorsements_loading",
×
559
                                        endorsement.append("status", toRetrieve.getValue()));
×
560
                            }
561
                        }
×
562
                    });
×
563
                }
564
                logger.debug("Pubkey {}: endorsement list loaded", pubkeyHash);
×
565

566
                set(s, "lists", endorseList.append("status", loaded.getValue()));
×
567

568
                Document df = new Document("pubkey", pubkeyHash).append("type", "$");
×
569
                if (!has(s, "lists", df)) {
×
570
                    insert(s, "lists",
×
571
                            df.append("status", encountered.getValue()));
×
572
                }
573

574
                set(s, "accounts_loading", agentAccount.append("status", visited.getValue()));
×
575

576
                schedule(s, LOAD_CORE.with("depth", depth).append("load-count", loadCount + 1));
×
577
            }
578

579
        }
×
580

581
        // At the end of this step, we have added new endorsement
582
        // links to yet-to-retrieve agent introductions:
583
        // ------------------------------------------------------------
584
        //
585
        //         o      ----endorses----> [intro]
586
        //    --> /#\  /o\___            (to-retrieve)
587
        //        / \  \_/^^^
588
        //         (visited)
589
        //
590
        //    ========[X] trust path
591
        //
592
        // ------------------------------------------------------------
593
        // Only one endorsement is shown here, but there are typically
594
        // several.
595

596
    },
597

598
    FINISH_ITERATION {
33✔
599
        public void run(ClientSession s, Document taskDoc) {
600

601
            int depth = taskDoc.getInteger("depth");
×
602
            int loadCount = taskDoc.getInteger("load-count");
×
603

604
            if (loadCount == 0) {
×
605
                logger.info("No new cores loaded; finishing iteration");
×
606
                schedule(s, CALCULATE_TRUST_SCORES);
×
607
            } else if (depth == MAX_TRUST_PATH_DEPTH) {
×
608
                logger.info("Maximum depth reached: {}", depth);
×
609
                schedule(s, CALCULATE_TRUST_SCORES);
×
610
            } else {
611
                logger.info("Progressing iteration at depth {}", depth + 1);
×
612
                schedule(s, LOAD_DECLARATIONS.with("depth", depth + 1));
×
613
            }
614

615
        }
×
616

617
    },
618

619
    CALCULATE_TRUST_SCORES {
33✔
620

621
        // DB read from: accounts, trustPaths
622
        // DB write to:  accounts
623

624
        public void run(ClientSession s, Document taskDoc) {
625
            logger.info("Running CALCULATE_TRUST_SCORES task");
×
626

627
            while (true) {
628
                Document d = getOne(s, "accounts_loading", new Document("status", expanded.getValue()));
×
629
                if (d == null) {
×
630
                    break;
×
631
                }
632

633
                double ratio = 0.0;
×
634
                Map<String, Boolean> seenPathElements = new HashMap<>();
×
635
                int pathCount = 0;
×
636
                try (MongoCursor<Document> trustPaths = collection("trustPaths_loading").find(s,
×
637
                        new Document("agent", d.get("agent").toString()).append("pubkey", d.get("pubkey").toString())
×
638
                ).sort(orderBy(ascending("depth"), descending("ratio"), ascending("sorthash"))).cursor()) {
×
639
                    while (trustPaths.hasNext()) {
×
640
                        Document trustPath = trustPaths.next();
×
641
                        ratio += trustPath.getDouble("ratio");
×
642
                        boolean independentPath = true;
×
643
                        String[] pathElements = trustPath.getString("_id").split(" ");
×
644
                        // Iterate over path elements, ignoring first (root) and last (this agent/pubkey):
645
                        for (int i = 1; i < pathElements.length - 1; i++) {
×
646
                            String p = pathElements[i];
×
647
                            if (seenPathElements.containsKey(p)) {
×
648
                                independentPath = false;
×
649
                                break;
×
650
                            }
651
                            seenPathElements.put(p, true);
×
652
                        }
653
                        if (independentPath) {
×
654
                            pathCount += 1;
×
655
                        }
656
                    }
×
657
                }
658
                double rawQuota = GLOBAL_QUOTA * ratio;
×
659
                int quota = (int) rawQuota;
×
660
                if (rawQuota < MIN_USER_QUOTA) {
×
661
                    quota = MIN_USER_QUOTA;
×
662
                } else if (rawQuota > MAX_USER_QUOTA) {
×
663
                    quota = MAX_USER_QUOTA;
×
664
                }
665
                set(s, "accounts_loading",
×
666
                        d.append("status", processed.getValue())
×
667
                                .append("ratio", ratio)
×
668
                                .append("pathCount", pathCount)
×
669
                                .append("quota", quota)
×
670
                );
671
            }
×
672
            logger.info("CALCULATE_TRUST_SCORES complete");
×
673
            schedule(s, AGGREGATE_AGENTS);
×
674
        }
×
675

676
    },
677

678
    AGGREGATE_AGENTS {
33✔
679

680
        // DB read from: accounts, agents
681
        // DB write to:  accounts, agents
682

683
        public void run(ClientSession s, Document taskDoc) {
684
            logger.info("Running AGGREGATE_AGENTS task");
×
685

686
            while (true) {
687
                Document a = getOne(s, "accounts_loading", new Document("status", processed.getValue()));
×
688
                if (a == null) {
×
689
                    break;
×
690
                }
691

692
                Document agentId = new Document("agent", a.get("agent").toString()).append("status", processed.getValue());
×
693
                int count = 0;
×
694
                int pathCountSum = 0;
×
695
                double totalRatio = 0.0d;
×
696
                // Canonical-name resolution across the agent's approved keys: pick the
697
                // row with MAX(ratio); ties broken on lex-min name for determinism.
698
                // Per-(agent, pubkey) name was already chosen by LOAD_ENDORSEMENTS as
699
                // "latest declaring intro wins"; this layer just folds across keys.
700
                String chosenName = null;
×
701
                double chosenRatio = Double.NEGATIVE_INFINITY;
×
702
                try (MongoCursor<Document> agentAccounts = collection("accounts_loading").find(s, agentId).cursor()) {
×
703
                    while (agentAccounts.hasNext()) {
×
704
                        Document d = agentAccounts.next();
×
705
                        count++;
×
706
                        pathCountSum += d.getInteger("pathCount");
×
707
                        double r = d.getDouble("ratio");
×
708
                        totalRatio += r;
×
709
                        String n = d.getString("name");
×
710
                        if (n != null && (r > chosenRatio
×
711
                                          || (r == chosenRatio && (chosenName == null || n.compareTo(chosenName) < 0)))) {
×
712
                            chosenName = n;
×
713
                            chosenRatio = r;
×
714
                        }
715
                    }
×
716
                }
717
                collection("accounts_loading").updateMany(s, agentId, new Document("$set",
×
718
                        new DbEntryWrapper(aggregated).getDocument()));
×
719
                insert(s, "agents_loading",
×
720
                        agentId.append("accountCount", count)
×
721
                                .append("avgPathCount", (double) pathCountSum / count)
×
722
                                .append("totalRatio", totalRatio)
×
723
                                .append("name", chosenName)
×
724
                );
725
            }
×
726
            logger.info("AGGREGATE_AGENTS complete");
×
727
            schedule(s, ASSIGN_PUBKEYS);
×
728

729
        }
×
730

731
    },
732

733
    ASSIGN_PUBKEYS {
33✔
734

735
        // DB read from: accounts
736
        // DB write to:  accounts
737

738
        public void run(ClientSession s, Document taskDoc) {
739
            logger.info("Running ASSIGN_PUBKEYS task");
×
740
            int approvedCount = 0;
×
741
            int contestedCount = 0;
×
742

743
            while (true) {
744
                Document a = getOne(s, "accounts_loading", new DbEntryWrapper(aggregated).getDocument());
×
745
                if (a == null) {
×
746
                    break;
×
747
                }
748

749
                Document pubkeyId = new Document("pubkey", a.get("pubkey").toString());
×
750
                if (collection("accounts_loading").countDocuments(s, pubkeyId) == 1) {
×
751
                    collection("accounts_loading").updateMany(s, pubkeyId,
×
752
                            new Document("$set", new DbEntryWrapper(approved).getDocument()));
×
753
                    approvedCount++;
×
754
                } else {
755
                    // TODO At the moment all get marked as 'contested'; implement more nuanced algorithm
756
                    logger.debug("Pubkey {} is claimed by multiple accounts; marking contested", pubkeyId.getString("pubkey"));
×
757
                    collection("accounts_loading").updateMany(s, pubkeyId, new Document("$set",
×
758
                            new DbEntryWrapper(contested).getDocument()));
×
759
                    contestedCount++;
×
760
                }
761
            }
×
762
            logger.info("ASSIGN_PUBKEYS complete: {} approved, {} contested", approvedCount, contestedCount);
×
763
            schedule(s, DETERMINE_UPDATES);
×
764

765
        }
×
766

767
    },
768

769
    DETERMINE_UPDATES {
33✔
770

771
        // DB read from: accounts
772
        // DB write to:  accounts
773

774
        public void run(ClientSession s, Document taskDoc) {
775
            logger.info("Running DETERMINE_UPDATES task");
×
776

777
            // TODO Handle contested accounts properly:
778
            for (Document d : collection("accounts_loading").find(
×
779
                    new DbEntryWrapper(approved).getDocument())) {
×
780
                // TODO Consider quota too:
781
                Document accountId = new Document("agent", d.get("agent").toString()).append("pubkey", d.get("pubkey").toString());
×
782
                if (collection(Collection.ACCOUNTS.toString()) == null || !has(s, Collection.ACCOUNTS.toString(),
×
783
                        accountId.append("status", loaded.getValue()))) {
×
784
                    set(s, "accounts_loading", d.append("status", toLoad.getValue()));
×
785
                } else {
786
                    set(s, "accounts_loading", d.append("status", loaded.getValue()));
×
787
                }
788
            }
×
789
            logger.info("DETERMINE_UPDATES complete");
×
790
            schedule(s, FINALIZE_TRUST_STATE);
×
791

792
        }
×
793

794
    },
795

796
    FINALIZE_TRUST_STATE {
33✔
797
        // We do this is a separate task/transaction, because if we do it at the beginning of RELEASE_DATA, that task hangs and cannot
798
        // properly re-run (as some renaming outside of transactions will have taken place).
799
        public void run(ClientSession s, Document taskDoc) {
800
            logger.info("Running FINALIZE_TRUST_STATE task");
×
801
            String newTrustStateHash = RegistryDB.calculateTrustStateHash(s);
×
802
            String previousTrustStateHash = (String) getValue(s, Collection.SERVER_INFO.toString(), "trustStateHash");  // may be null
×
803
            logger.info("Computed new trust state hash {} (previous: {})", newTrustStateHash, previousTrustStateHash);
×
804
            setValue(s, Collection.SERVER_INFO.toString(), "lastTrustStateUpdate", ZonedDateTime.now().toString());
×
805

806
            schedule(s, RELEASE_DATA.with("newTrustStateHash", newTrustStateHash).append("previousTrustStateHash", previousTrustStateHash));
×
807
        }
×
808

809
    },
810

811
    RELEASE_DATA {
33✔
812

813
        private static final int TRUST_STATE_SNAPSHOT_RETENTION = 100;
814

815
        public void run(ClientSession s, Document taskDoc) {
816
            ServerStatus status = getServerStatus(s);
×
817
            logger.info("Running RELEASE_DATA task (current status: {})", status);
×
818

819
            String newTrustStateHash = taskDoc.get("newTrustStateHash").toString();
×
820
            String previousTrustStateHash = taskDoc.getString("previousTrustStateHash");  // may be null
×
821

822
            // Renaming collections is run outside of a transaction, but is idempotent operation, so can safely be retried if task fails:
823
            logger.debug("Renaming loading collections into live collections");
×
824
            rename("accounts_loading", Collection.ACCOUNTS.toString());
×
825
            rename("trustPaths_loading", "trustPaths");
×
826
            rename("agents_loading", Collection.AGENTS.toString());
×
827
            rename("endorsements_loading", "endorsements");
×
828

829
            if (previousTrustStateHash == null || !previousTrustStateHash.equals(newTrustStateHash)) {
×
830
                logger.info("Trust state changed ({} -> {}); recording new state and snapshot", previousTrustStateHash, newTrustStateHash);
×
831
                increaseStateCounter(s);
×
832
                setValue(s, Collection.SERVER_INFO.toString(), "trustStateHash", newTrustStateHash);
×
833
                Object trustStateCounter = getValue(s, Collection.SERVER_INFO.toString(), "trustStateCounter");
×
834
                insert(s, "debug_trustPaths", new Document()
×
835
                        .append("trustStateTxt", DebugPage.getTrustPathsTxt(s))
×
836
                        .append("trustStateHash", newTrustStateHash)
×
837
                        .append("trustStateCounter", trustStateCounter)
×
838
                );
839

840
                // Structured hash-keyed snapshot for consumer mirroring (#107).
841
                // Reads the accounts collection just renamed from accounts_loading above (:697).
842
                List<Document> snapshotAccounts = new ArrayList<>();
×
843
                for (Document a : collection(Collection.ACCOUNTS.toString()).find(s)) {
×
844
                    String pubkey = a.getString("pubkey");
×
845
                    if ("$".equals(pubkey)) {
×
846
                        continue;
×
847
                    }
848
                    snapshotAccounts.add(new Document()
×
849
                            .append("pubkey", pubkey)
×
850
                            .append("agent", a.getString("agent"))
×
851
                            .append("name", a.getString("name"))
×
852
                            .append("nameCreatedAt", a.get("nameCreatedAt"))
×
853
                            .append("status", a.getString("status"))
×
854
                            .append("depth", a.get("depth"))
×
855
                            .append("pathCount", a.get("pathCount"))
×
856
                            .append("ratio", a.get("ratio"))
×
857
                            .append("quota", a.get("quota")));
×
858
                }
×
859
                Document snapshot = new Document()
×
860
                        .append("_id", newTrustStateHash)
×
861
                        .append("trustStateCounter", trustStateCounter)
×
862
                        .append("createdAt", ZonedDateTime.now().toString())
×
863
                        .append("accounts", snapshotAccounts);
×
864
                collection(Collection.TRUST_STATE_SNAPSHOTS.toString()).replaceOne(
×
865
                        s,
866
                        new Document("_id", newTrustStateHash),
867
                        snapshot,
868
                        new ReplaceOptions().upsert(true));
×
869
                logger.debug("Saved trust state snapshot {} with {} account(s)", newTrustStateHash, snapshotAccounts.size());
×
870

871
                // Prune beyond retention: collect _ids of snapshots past the Nth most recent, delete them.
872
                // trustStateCounter is monotonically increasing (see increaseStateCounter above), so ordering is well-defined.
873
                List<Object> toPrune = new ArrayList<>();
×
874
                try (MongoCursor<Document> stale = collection(Collection.TRUST_STATE_SNAPSHOTS.toString())
×
875
                        .find(s)
×
876
                        .sort(descending("trustStateCounter"))
×
877
                        .skip(TRUST_STATE_SNAPSHOT_RETENTION)
×
878
                        .projection(new Document("_id", 1))
×
879
                        .cursor()) {
×
880
                    while (stale.hasNext()) {
×
881
                        toPrune.add(stale.next().get("_id"));
×
882
                    }
883
                }
884
                if (!toPrune.isEmpty()) {
×
885
                    logger.info("Pruning {} trust state snapshot(s) beyond retention limit of {}", toPrune.size(), TRUST_STATE_SNAPSHOT_RETENTION);
×
886
                    collection(Collection.TRUST_STATE_SNAPSHOTS.toString()).deleteMany(
×
887
                            s, new Document("_id", new Document("$in", toPrune)));
888
                }
889
            } else {
×
890
                logger.info("Trust state unchanged ({}); skipping snapshot and pruning", newTrustStateHash);
×
891
            }
892

893
            if (status == coreLoading) {
×
894
                logger.info("Server status transitioning coreLoading -> coreReady");
×
895
                setServerStatus(s, coreReady);
×
896
            } else {
897
                logger.info("Server status transitioning {} -> ready", status);
×
898
                setServerStatus(s, ready);
×
899
            }
900

901
            // Run update after 1h:
902
            logger.debug("RELEASE_DATA complete; scheduling next UPDATE in 1h");
×
903
            schedule(s, UPDATE.withDelay(60 * 60 * 1000));
×
904
        }
×
905

906
    },
907

908
    UPDATE {
33✔
909
        public void run(ClientSession s, Document taskDoc) {
910
            ServerStatus status = getServerStatus(s);
×
911
            if (status == ready || status == coreReady) {
×
912
                logger.info("Server status {} eligible for update; transitioning to updating and scheduling INIT_COLLECTIONS", status);
×
913
                setServerStatus(s, updating);
×
914
                schedule(s, INIT_COLLECTIONS);
×
915
            } else {
916
                logger.info("Postponing update; currently in status {}", status);
×
917
                schedule(s, UPDATE.withDelay(10 * 60 * 1000));
×
918
            }
919

920
        }
×
921

922
    },
923

924
    LOAD_FULL {
33✔
925
        public void run(ClientSession s, Document taskDoc) {
926
            logger.debug("LOAD_FULL invoked; taskDoc={}", taskDoc);
12✔
927

928
            if ("false".equals(System.getenv("REGISTRY_PERFORM_FULL_LOAD"))) {
15!
929
                logger.info("REGISTRY_PERFORM_FULL_LOAD=false; skipping full load");
×
930
                return;
×
931
            }
932

933
            ServerStatus status = getServerStatus(s);
9✔
934
            logger.debug("Server status check for LOAD_FULL: status={}", status);
12✔
935
            if (status != coreReady && status != ready && status != updating) {
27!
936
                long delay = 1000;
6✔
937
                logger.info("Server status={} is not eligible for full load (expected coreReady/ready/updating); deferring and retrying in {}ms", status, delay);
18✔
938
                schedule(s, LOAD_FULL.withDelay(delay));
15✔
939
                return;
3✔
940
            }
941

942
            Document a = getOne(s, Collection.ACCOUNTS.toString(), new DbEntryWrapper(toLoad).getDocument());
×
943
            if (a == null) {
×
944
                logger.info("No accounts left with status={}; full load pass complete", toLoad);
×
945
                if (status == coreReady) {
×
946
                    logger.info("Server status transitioning coreReady -> ready; full load finished");
×
947
                    setServerStatus(s, ready);
×
948
                }
949
                long delay = 100;
×
950
                logger.info("Scheduling optional loading checks (RUN_OPTIONAL_LOAD) in {}ms", delay);
×
951
                schedule(s, RUN_OPTIONAL_LOAD.withDelay(delay));
×
952
            } else {
×
953
                final String ph = a.getString("pubkey");
×
954
                boolean quotaReached = false;
×
955
                if (!ph.equals("$")) {
×
956
                    if (!AgentFilter.isAllowed(s, ph)) {
×
957
                        logger.info("Pubkey {} is not covered by the agent filter; marking account as skipped", ph);
×
958
                        set(s, Collection.ACCOUNTS.toString(), a.append("status", skipped.getValue()));
×
959
                        schedule(s, LOAD_FULL.withDelay(100));
×
960
                        return;
×
961
                    }
962
                    if (AgentFilter.isOverQuota(s, ph)) {
×
963
                        logger.info("Pubkey {} is already over quota; skipping load, marking account as capped", ph);
×
964
                        quotaReached = true;
×
965
                    } else {
966
                        long startTime = System.nanoTime();
×
967
                        AtomicLong totalLoaded = new AtomicLong(0);
×
968

969
                        // Load per covered type (or "$" if no restriction) with checksum skip-ahead
970
                        for (String typeHash : getLoadTypeHashes(s, ph)) {
×
971
                            logger.debug("Pubkey {}: starting load for typeHash={}", ph, typeHash);
×
972
                            String checksums = buildChecksumFallbacks(s, ph, typeHash);
×
973
                            logger.debug("Pubkey {}, typeHash={}: checksum fallbacks={}", ph, typeHash, checksums);
×
974
                            try (var stream = NanopubLoader.retrieveNanopubsFromPeers(typeHash, ph, checksums)) {
×
975
                                NanopubLoader.loadStreamInParallel(stream, np -> {
×
976
                                    if (!CoverageFilter.isCovered(np)) {
×
977
                                        logger.debug("Pubkey {}: nanopub {} not covered; skipping", ph, np);
×
978
                                        return;
×
979
                                    }
980
                                    try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
981
                                        if (!AgentFilter.isOverQuota(ws, ph)) {
×
982
                                            loadNanopub(ws, np, ph, "$");
×
983
                                            totalLoaded.incrementAndGet();
×
984
                                        } else {
985
                                            logger.debug("Pubkey {} hit quota mid-stream; skipping nanopub {}", ph, np);
×
986
                                        }
987
                                    }
988
                                });
×
989
                            }
990
                            logger.debug("Pubkey {}: finished load for typeHash={}", ph, typeHash);
×
991
                        }
×
992

993
                        double timeSeconds = (System.nanoTime() - startTime) * 1e-9;
×
994
                        logger.info("Pubkey {}: loaded {} nanopubs in {}s ({} np/s)",
×
995
                                ph, totalLoaded.get(), String.format("%.2f", timeSeconds),
×
996
                                String.format("%.2f", totalLoaded.get() / timeSeconds));
×
997

998
                        if (AgentFilter.isOverQuota(s, ph)) {
×
999
                            logger.info("Pubkey {} reached quota during this load; marking account as capped", ph);
×
1000
                            quotaReached = true;
×
1001
                        }
1002
                    }
×
1003
                } else {
1004
                    logger.debug("Account pubkey is '$' (unrestricted); no per-pubkey quota/filter checks applied");
×
1005
                }
1006

1007
                Document l = getOne(s, "lists", new Document().append("pubkey", ph).append("type", "$"));
×
1008
                if (l != null) {
×
1009
                    logger.debug("Pubkey {}: marking matching list entry as loaded", ph);
×
1010
                    set(s, "lists", l.append("status", loaded.getValue()));
×
1011
                }
1012
                EntryStatus accountStatus = quotaReached ? capped : loaded;
×
1013
                int effectiveQuota = AgentFilter.getQuota(s, ph);
×
1014
                if (effectiveQuota >= 0) {
×
1015
                    logger.debug("Pubkey {}: recording effective quota={}", ph, effectiveQuota);
×
1016
                    a.append("quota", effectiveQuota);
×
1017
                }
1018
                logger.info("Pubkey {}: account load complete, status={}", ph, accountStatus);
×
1019
                set(s, Collection.ACCOUNTS.toString(), a.append("status", accountStatus.getValue()));
×
1020

1021
                schedule(s, LOAD_FULL.withDelay(100));
×
1022
            }
1023
        }
×
1024

1025
        @Override
1026
        public boolean runAsTransaction() {
1027
            // TODO Make this a transaction once we connect to other Nanopub Registry instances:
1028
            return false;
×
1029
        }
1030

1031
    },
1032

1033
    RUN_OPTIONAL_LOAD {
33✔
1034

1035
        private static final int BATCH_SIZE = Integer.parseInt(
15✔
1036
                Utils.getEnv("REGISTRY_OPTIONAL_LOAD_BATCH_SIZE", "100"));
3✔
1037

1038
        public void run(ClientSession s, Document taskDoc) {
1039
            if ("false".equals(System.getenv("REGISTRY_ENABLE_OPTIONAL_LOAD"))) {
×
1040
                schedule(s, CHECK_NEW.withDelay(500));
×
1041
                return;
×
1042
            }
1043

1044
            AtomicLong totalLoaded = new AtomicLong(0);
×
1045

1046
            // Phase 1: Process encountered intro lists (core loading)
1047
            while (totalLoaded.get() < BATCH_SIZE) {
×
1048
                Document di = getOne(s, "lists", new Document("type", INTRO_TYPE_HASH).append("status", encountered.getValue()));
×
1049
                if (di == null) {
×
1050
                    break;
×
1051
                }
1052

1053
                final String pubkeyHash = di.getString("pubkey");
×
1054
                Validate.notNull(pubkeyHash);
×
1055
                logger.info("Optional core loading: {}", pubkeyHash);
×
1056

1057
                String introChecksums = buildChecksumFallbacks(s, pubkeyHash, INTRO_TYPE_HASH);
×
1058
                try (var stream = NanopubLoader.retrieveNanopubsFromPeers(INTRO_TYPE_HASH, pubkeyHash, introChecksums)) {
×
1059
                    NanopubLoader.loadStreamInParallel(stream, np -> {
×
1060
                        try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
1061
                            loadNanopub(ws, np, pubkeyHash, INTRO_TYPE);
×
1062
                            totalLoaded.incrementAndGet();
×
1063
                        }
1064
                    });
×
1065
                }
1066
                set(s, "lists", di.append("status", loaded.getValue()));
×
1067

1068
                String endorseChecksums = buildChecksumFallbacks(s, pubkeyHash, ENDORSE_TYPE_HASH);
×
1069
                try (var stream = NanopubLoader.retrieveNanopubsFromPeers(ENDORSE_TYPE_HASH, pubkeyHash, endorseChecksums)) {
×
1070
                    NanopubLoader.loadStreamInParallel(stream, np -> {
×
1071
                        try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
1072
                            loadNanopub(ws, np, pubkeyHash, ENDORSE_TYPE);
×
1073
                            totalLoaded.incrementAndGet();
×
1074
                        }
1075
                    });
×
1076
                }
1077

1078
                Document de = new Document("pubkey", pubkeyHash).append("type", ENDORSE_TYPE_HASH);
×
1079
                if (has(s, "lists", de)) {
×
1080
                    set(s, "lists", de.append("status", loaded.getValue()));
×
1081
                } else {
1082
                    insert(s, "lists", de.append("status", loaded.getValue()));
×
1083
                }
1084

1085
                Document df = new Document("pubkey", pubkeyHash).append("type", "$");
×
1086
                if (!has(s, "lists", df)) {
×
1087
                    insert(s, "lists", df.append("status", encountered.getValue()));
×
1088
                }
1089
            }
×
1090

1091
            // Phase 2: Process encountered full lists (if budget remains)
1092
            while (totalLoaded.get() < BATCH_SIZE) {
×
1093
                Document df = getOne(s, "lists", new Document("type", "$").append("status", encountered.getValue()));
×
1094
                if (df == null) {
×
1095
                    break;
×
1096
                }
1097

1098
                final String pubkeyHash = df.getString("pubkey");
×
1099
                logger.info("Optional full loading: {}", pubkeyHash);
×
1100

1101
                // Load per covered type (or "$" if no restriction) with checksum skip-ahead
1102
                for (String typeHash : getLoadTypeHashes(s, pubkeyHash)) {
×
1103
                    String checksums = buildChecksumFallbacks(s, pubkeyHash, typeHash);
×
1104
                    try (var stream = NanopubLoader.retrieveNanopubsFromPeers(typeHash, pubkeyHash, checksums)) {
×
1105
                        NanopubLoader.loadStreamInParallel(stream, np -> {
×
1106
                            if (!CoverageFilter.isCovered(np)) {
×
1107
                                return;
×
1108
                            }
1109
                            try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
1110
                                loadNanopub(ws, np, pubkeyHash, "$");
×
1111
                                totalLoaded.incrementAndGet();
×
1112
                            }
1113
                        });
×
1114
                    }
1115
                }
×
1116

1117
                set(s, "lists", df.append("status", loaded.getValue()));
×
1118

1119
                // Backfill nanopubs stored locally during the transitional period (i.e. before
1120
                // the $ list was loaded). Such nanopubs were stored in the nanopubs collection by
1121
                // simpleLoad() but never added to listEntries; add them to the $ list now.
1122
                logger.info("Backfilling locally stored nanopubs for pubkey: {}", pubkeyHash);
×
1123
                try (MongoCursor<Document> npCursor = collection(Collection.NANOPUBS.toString())
×
1124
                        .find(s, new Document("pubkey", pubkeyHash)).cursor()) {
×
1125
                    while (npCursor.hasNext()) {
×
1126
                        String fullId = npCursor.next().getString("fullId");
×
1127
                        if (fullId == null) {
×
1128
                            continue;
×
1129
                        }
1130
                        try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
1131
                            Nanopub np = NanopubLoader.retrieveLocalNanopub(ws, fullId);
×
1132
                            if (np != null && CoverageFilter.isCovered(np)) {
×
1133
                                loadNanopub(ws, np, pubkeyHash, "$");
×
1134
                                totalLoaded.incrementAndGet();
×
1135
                            }
1136
                        } catch (Exception ex) {
×
1137
                            logger.info("Error backfilling nanopub {}: {}", fullId, ex.getMessage());
×
1138
                        }
×
1139
                    }
×
1140
                }
1141
            }
×
1142

1143
            if (totalLoaded.get() > 0) {
×
1144
                logger.info("Optional load batch completed: {} nanopubs across multiple pubkeys", totalLoaded.get());
×
1145
            }
1146

1147
            if (prioritizeAllPubkeys()) {
×
1148
                // Check if there are more pubkeys waiting to be processed
1149
                boolean moreWork = has(s, "lists", new Document("type", INTRO_TYPE_HASH).append("status", encountered.getValue()))
×
1150
                                   || has(s, "lists", new Document("type", "$").append("status", encountered.getValue()));
×
1151
                if (moreWork) {
×
1152
                    // Continue processing without a full CHECK_NEW cycle in between.
1153
                    // CHECK_NEW will run naturally once all encountered lists are processed.
1154
                    schedule(s, RUN_OPTIONAL_LOAD.withDelay(10));
×
1155
                } else {
1156
                    schedule(s, CHECK_NEW.withDelay(500));
×
1157
                }
1158
            } else {
×
1159
                // Throttled: yield to CHECK_NEW after each batch to prioritize approved pubkeys
1160
                schedule(s, CHECK_NEW.withDelay(500));
×
1161
            }
1162
        }
×
1163

1164
    },
1165

1166
    CHECK_NEW {
33✔
1167
        public void run(ClientSession s, Document taskDoc) {
1168
            logger.debug("Running CHECK_NEW task: checking peers and legacy source for new nanopubs");
×
1169

1170
            logger.debug("Checking peers for new nanopubs");
×
1171
            RegistryPeerConnector.checkPeers(s);
×
1172
            // Keep legacy connection during transition period:
1173
            logger.debug("Checking legacy connector for new nanopubs");
×
1174
            LegacyConnector.checkForNewNanopubs(s);
×
1175
            // TODO Somehow throttle the loading of such potentially non-approved nanopubs
1176

1177
            long delay = 100;
×
1178
            logger.debug("CHECK_NEW complete; scheduling LOAD_FULL with {}ms delay", delay);
×
1179
            schedule(s, LOAD_FULL.withDelay(delay));
×
1180
        }
×
1181

1182
        @Override
1183
        public boolean runAsTransaction() {
1184
            // Peer sync includes long-running streaming fetches that would exceed
1185
            // MongoDB's transaction timeout; each operation is individually safe.
1186
            return false;
×
1187
        }
1188

1189
    };
1190

1191
    private static final Logger logger = LoggerFactory.getLogger(Task.class);
9✔
1192

1193
    public abstract void run(ClientSession s, Document taskDoc) throws Exception;
1194

1195
    public boolean runAsTransaction() {
1196
        return true;
×
1197
    }
1198

1199
    Document asDocument() {
1200
        return withDelay(0L);
12✔
1201
    }
1202

1203
    private Document withDelay(long delay) {
1204
        // TODO Rename "not-before" to "notBefore" for consistency with other field names
1205
        return new Document()
15✔
1206
                .append("not-before", System.currentTimeMillis() + delay)
21✔
1207
                .append("action", name());
6✔
1208
    }
1209

1210
    private Document with(String key, Object value) {
1211
        return asDocument().append(key, value);
×
1212
    }
1213

1214
    private static boolean prioritizeAllPubkeys() {
1215
        return "true".equals(System.getenv("REGISTRY_PRIORITIZE_ALL_PUBKEYS"));
×
1216
    }
1217

1218
    /**
1219
     * Returns the type hashes to load for a given pubkey. When coverage is unrestricted,
1220
     * returns just "$" (all types in one request). When restricted, returns each covered
1221
     * type hash for per-type fetching with checksum skip-ahead.
1222
     * <p>
1223
     * TODO: Fetching "$" from peers with type restrictions will only return their covered
1224
     * types, not all types. To get full coverage, we'd need to fetch per-type from such peers.
1225
     * Additionally, checksum-based skip-ahead won't work correctly against such peers, because
1226
     * their "$" list has different checksums due to the differing type subset. This means full
1227
     * re-downloads on every cycle. Per-type fetching would solve both issues.
1228
     */
1229
    private static java.util.List<String> getLoadTypeHashes(ClientSession s, String pubkeyHash) {
1230
        if (CoverageFilter.coversAllTypes()) {
×
1231
            return java.util.List.of("$");
×
1232
        }
1233
        return java.util.List.copyOf(CoverageFilter.getCoveredTypeHashes());
×
1234
    }
1235

1236
    // TODO Move these to setting:
1237
    private static final int MAX_TRUST_PATH_DEPTH = 10;
1238
    private static final double MIN_TRUST_PATH_RATIO = 0.0000000001;
1239
    //private static final double MIN_TRUST_PATH_RATIO = 0.01; // For testing
1240
    private static final int GLOBAL_QUOTA = Integer.parseInt(
12✔
1241
            Utils.getEnv("REGISTRY_GLOBAL_QUOTA", "1000000000"));
3✔
1242
    private static final int MIN_USER_QUOTA = Integer.parseInt(
12✔
1243
            Utils.getEnv("REGISTRY_MIN_USER_QUOTA", "1000"));
3✔
1244
    private static final int MAX_USER_QUOTA = Integer.parseInt(
12✔
1245
            Utils.getEnv("REGISTRY_MAX_USER_QUOTA", "100000"));
3✔
1246

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

1249
    private static volatile String currentTaskName;
1250
    private static volatile long currentTaskStartTime;
1251

1252
    public static String getCurrentTaskName() {
1253
        return currentTaskName;
×
1254
    }
1255

1256
    public static long getCurrentTaskStartTime() {
1257
        return currentTaskStartTime;
×
1258
    }
1259

1260
    /**
1261
     * The super important base entry point!
1262
     */
1263
    static void runTasks() {
1264
        try (ClientSession s = RegistryDB.getClient().startSession()) {
×
1265
            if (!RegistryDB.isInitialized(s)) {
×
1266
                schedule(s, INIT_DB); // does not yet execute, only schedules
×
1267
            }
1268

1269
            logger.info("Task runner started");
×
1270
            while (true) {
1271
                FindIterable<Document> taskResult = tasksCollection.find(s).sort(ascending("not-before"));
×
1272
                Document taskDoc = taskResult.first();
×
1273
                long sleepTime = 10;
×
1274
                if (taskDoc != null && taskDoc.getLong("not-before") < System.currentTimeMillis()) {
×
1275
                    Task task = valueOf(taskDoc.getString("action"));
×
1276
                    Object taskId = taskDoc.getOrDefault("_id", null);
×
1277
                    logger.info("Picked task to run: {} (docId={})", task.name(), taskId);
×
1278

1279
                    if (task.runAsTransaction()) {
×
1280
                        try {
1281
                            s.startTransaction();
×
1282
                            logger.debug("Transaction started for task {}", task.name());
×
1283
                            runTask(task, taskDoc);
×
1284
                            s.commitTransaction();
×
1285
                            logger.info("Transaction committed for task {}", task.name());
×
1286
                        } catch (Exception ex) {
×
1287
                            logger.warn("Transactional task {} failed, aborting: {}", task.name(), ex.getMessage(), ex);
×
1288
                            abortTransaction(s, ex.getMessage());
×
1289
                            logger.info("Transaction aborted for task {}", task.name());
×
1290
                            sleepTime = 1000;
×
1291
                        } finally {
1292
                            cleanTransactionWithRetry(s);
×
1293
                        }
×
1294
                    } else {
1295
                        try {
1296
                            runTask(task, taskDoc);
×
1297
                        } catch (Exception ex) {
×
1298
                            logger.warn("Non-transactional task {} failed: {}", task.name(), ex.getMessage(), ex);
×
1299
                        }
×
1300
                    }
1301
                }
1302
                try {
1303
                    Thread.sleep(sleepTime);
×
1304
                } catch (InterruptedException ex) {
×
1305
                    // ignore
1306
                    logger.debug("Task runner sleep interrupted");
×
1307
                }
×
1308
            }
×
1309
        }
1310
    }
1311

1312
    static void runTask(Task task, Document taskDoc) throws Exception {
1313
        currentTaskName = task.name();
9✔
1314
        currentTaskStartTime = System.currentTimeMillis();
6✔
1315
        logger.info("Starting task {} with request: {}", currentTaskName, taskDoc);
15✔
1316

1317
        try (ClientSession s = RegistryDB.getClient().startSession()) {
9✔
1318
            task.run(s, taskDoc);
12✔
1319
            long duration = System.currentTimeMillis() - currentTaskStartTime;
12✔
1320
            tasksCollection.deleteOne(s, eq("_id", taskDoc.get("_id")));
27✔
1321
            logger.info("Completed and removed from queue task {} in {} ms", currentTaskName, duration);
18✔
1322
        } catch (Exception ex) {
×
1323
            long duration = System.currentTimeMillis() - currentTaskStartTime;
×
1324
            logger.error("Task {} failed after {} ms: {}", currentTaskName, duration, ex.getMessage(), ex);
×
1325
            throw ex;
×
1326
        } finally {
1327
            currentTaskName = null;
6✔
1328
        }
1329
    }
3✔
1330

1331
    public static void abortTransaction(ClientSession mongoSession, String message) {
1332
        boolean successful = false;
×
1333
        while (!successful) {
×
1334
            try {
1335
                if (mongoSession.hasActiveTransaction()) {
×
1336
                    logger.info("Attempting to abort transaction: {}", message);
×
1337
                    mongoSession.abortTransaction();
×
1338
                }
1339
                successful = true;
×
1340
                logger.debug("abortTransaction succeeded");
×
1341
            } catch (Exception ex) {
×
1342
                logger.warn("abortTransaction attempt failed: {}", ex.getMessage(), ex);
×
1343
                try {
1344
                    Thread.sleep(100);
×
1345
                } catch (InterruptedException ie) {
×
1346
                    logger.debug("abortTransaction sleep interrupted");
×
1347
                }
×
1348
            }
×
1349
        }
1350
    }
×
1351

1352
    public synchronized static void cleanTransactionWithRetry(ClientSession mongoSession) {
1353
        boolean successful = false;
×
1354
        while (!successful) {
×
1355
            try {
1356
                if (mongoSession.hasActiveTransaction()) {
×
1357
                    mongoSession.abortTransaction();
×
1358
                    logger.debug("abortTransaction during cleanup succeeded");
×
1359
                }
1360
                successful = true;
×
1361
                logger.debug("Transaction cleanup completed");
×
1362
            } catch (Exception ex) {
×
1363
                logger.warn("Transaction cleanup failed: {}", ex.getMessage(), ex);
×
1364
                try {
1365
                    Thread.sleep(100);
×
1366
                } catch (InterruptedException ie) {
×
1367
                    logger.debug("cleanTransactionWithRetry sleep interrupted");
×
1368
                }
×
1369
            }
×
1370
        }
1371
    }
×
1372

1373
    private static IntroNanopub getAgentIntro(ClientSession mongoSession, String nanopubId) {
1374
        IntroNanopub agentIntro = new IntroNanopub(NanopubLoader.retrieveNanopub(mongoSession, nanopubId));
×
1375
        if (agentIntro.getUser() == null) {
×
1376
            logger.debug("Nanopub {} is not a valid agent intro (no declared user); discarding", nanopubId);
×
1377
            return null;
×
1378
        }
1379
        loadNanopub(mongoSession, agentIntro.getNanopub());
×
1380
        return agentIntro;
×
1381
    }
1382

1383

1384
    private static void setServerStatus(ClientSession mongoSession, ServerStatus status) {
1385
        setValue(mongoSession, Collection.SERVER_INFO.toString(), "status", status.toString());
21✔
1386
    }
3✔
1387

1388
    private static ServerStatus getServerStatus(ClientSession mongoSession) {
1389
        Object status = getValue(mongoSession, Collection.SERVER_INFO.toString(), "status");
18✔
1390
        if (status == null) {
6!
1391
            throw new RuntimeException("Illegal DB state: serverInfo status unavailable");
×
1392
        }
1393
        return ServerStatus.valueOf(status.toString());
12✔
1394
    }
1395

1396
    private static void schedule(ClientSession mongoSession, Task task) {
1397
        schedule(mongoSession, task.asDocument());
12✔
1398
    }
3✔
1399

1400
    private static void schedule(ClientSession mongoSession, Document taskDoc) {
1401
        logger.info("Scheduling task: {}", taskDoc.getString("action"));
18✔
1402
        tasksCollection.insertOne(mongoSession, taskDoc);
12✔
1403
    }
3✔
1404

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