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

knowledgepixels / nanopub-query / 31705923878

13 Aug 2026 01:38PM UTC coverage: 76.437% (+0.2%) from 76.255%
31705923878

push

github

web-flow
Merge pull request #187 from knowledgepixels/feat/protected-nanopub

feat: recognize npx:ProtectedNanopub type

836 of 1238 branches covered (67.53%)

Branch coverage included in aggregate %.

2463 of 3078 relevant lines covered (80.02%)

12.5 hits per line

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

72.36
src/main/java/com/knowledgepixels/query/NanopubLoader.java
1
package com.knowledgepixels.query;
2

3
import net.trustyuri.TrustyUriUtils;
4
import org.apache.http.client.HttpClient;
5
import org.apache.http.impl.client.HttpClientBuilder;
6
import org.eclipse.rdf4j.common.exception.RDF4JException;
7
import org.eclipse.rdf4j.common.transaction.IsolationLevels;
8
import org.eclipse.rdf4j.model.*;
9
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
10
import org.eclipse.rdf4j.model.vocabulary.DCTERMS;
11
import org.eclipse.rdf4j.model.vocabulary.RDFS;
12
import org.eclipse.rdf4j.query.BindingSet;
13
import org.eclipse.rdf4j.query.QueryLanguage;
14
import org.eclipse.rdf4j.query.TupleQuery;
15
import org.eclipse.rdf4j.query.TupleQueryResult;
16
import org.eclipse.rdf4j.repository.RepositoryConnection;
17
import org.eclipse.rdf4j.repository.RepositoryResult;
18
import org.nanopub.Nanopub;
19
import org.nanopub.NanopubUtils;
20
import org.nanopub.SimpleCreatorPattern;
21
import org.nanopub.SimpleTimestampPattern;
22
import org.nanopub.extra.security.KeyDeclaration;
23
import org.nanopub.extra.security.MalformedCryptoElementException;
24
import org.nanopub.extra.security.NanopubSignatureElement;
25
import org.nanopub.extra.security.SignatureUtils;
26
import org.nanopub.extra.server.GetNanopub;
27
import org.nanopub.extra.server.NanopubServerUtils;
28
import org.nanopub.extra.setting.IntroNanopub;
29
import org.nanopub.vocabulary.NP;
30
import org.nanopub.vocabulary.NPA;
31
import org.nanopub.vocabulary.NPX;
32
import org.nanopub.vocabulary.PAV;
33
import org.slf4j.Logger;
34
import org.slf4j.LoggerFactory;
35

36
import java.security.GeneralSecurityException;
37
import java.util.*;
38
import java.util.concurrent.*;
39
import java.util.concurrent.locks.ReentrantLock;
40
import java.util.function.Consumer;
41

42
/**
43
 * Utility class for loading nanopublications into the database.
44
 */
45
public class NanopubLoader {
46

47
    private static HttpClient httpClient;
48
    private static final ThreadPoolExecutor loadingPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(4);
12 ✔
49

50
    /**
51
     * One write lock per repo, held for the whole read-modify-write of that repo's
52
     * nanopub count / XOR checksum chain.
53
     *
54
     * <p>This replaces {@code IsolationLevels.SERIALIZABLE} as the mechanism protecting the
55
     * chain, and it is a strictly local substitution: this process is the only writer of
56
     * those triples, so in-process mutual exclusion gives exactly what the serializable
57
     * transaction was buying. The chain invariant is unchanged.
58
     *
59
     * <p>Why bother: in RDF4J 5.3.x, {@code SailSourceBranch.derivedFromSerializable} sets a
60
     * branch-level {@code serializable} sink the first time <em>any</em> transaction on that
61
     * branch asks for a SERIALIZABLE-compatible level, and clears it only when the branch
62
     * closes. While it is set, every dataset opened on that branch — including ordinary read
63
     * queries at any isolation — is wrapped in an {@code ObservingSailDataset}, which on close
64
     * runs {@code compressChanges -> prepare -> sinkObserved -> Changeset.observeAll} while
65
     * holding the branch semaphore. Hashing observed {@code SimpleStatementPattern}s there is
66
     * expensive ({@code LmdbIRI.hashCode} goes to a synchronized {@code ValueStore} map), so
67
     * one writer can stall every reader of the repo.
68
     *
69
     * <p>Measured on kpxl 2026-08-05: a thread dump showed 171 threads parked on a single
70
     * {@code ReentrantLock} in {@code derivedFromSerializable} for the {@code full} repo, one
71
     * thread inside {@code observeAll}, and the whole servlet container unable to answer even
72
     * a 404 for a nonexistent repo. Dropping to SNAPSHOT leaves {@code serializable} null, so
73
     * no {@code ObservingSailDataset} is created, {@code observed} stays null and
74
     * {@code sinkObserved} early-returns.
75
     *
76
     * <p>Keyed by repo name, so writers to different repos never contend. Calls are never
77
     * nested across repos — the invalidator paths loop and call one repo at a time — so there
78
     * is no lock-ordering hazard.
79
     *
80
     * <p>SERIALIZABLE is avoided codebase-wide, not just on this path: besides the
81
     * branch-tainting above, the LMDB native-heap corruption behind the rdf4j crash loop
82
     * (rdf4j #5970) is reported upstream to occur only under SERIALIZABLE transactions.
83
     * Every write path in this process is single-writer (in-process locks, synchronized
84
     * singletons, or single scheduled threads), so SNAPSHOT (for rewrites of existing
85
     * state) or READ_COMMITTED (for append-only writes) is always sufficient.
86
     */
87
    private static final ConcurrentHashMap<String, ReentrantLock> repoWriteLocks = new ConcurrentHashMap<>();
12 ✔
88

89
    static ReentrantLock repoWriteLock(String repoName) {
90
        return repoWriteLocks.computeIfAbsent(repoName, k -> new ReentrantLock());
30 ✔
91
    }
92

93
    /**
94
     * Cached count of nanopubs ever loaded into the {@code meta} repo. Maintained
95
     * for {@link MainVerticle}'s {@code Nanopub-Query-Loaded-Nanopub-Count}
96
     * response header. Mirrors the persisted {@code npa:hasNanopubCount} triple
97
     * that {@link #loadNanopubToRepo} maintains; invalidations don't decrement
98
     * (they're recorded as separate {@code npx:invalidates} markers), so this
99
     * is a cumulative count including superseded/retracted nanopubs — matching
100
     * the registry-side {@code Nanopub-Registry-Nanopub-Count} semantics.
101
     *
102
     * <p>The {@code meta} repo (not {@code full}) is the source because the meta
103
     * task is submitted only after all other per-nanopub tasks succeed (see
104
     * {@link #executeLoading}), making it the authoritative "fully completed
105
     * loads" indicator. The {@code full} repo is feature-flagged and may be
106
     * disabled, in which case it cannot be the source. Populated lazily on first
107
     * read; bumped post-commit on each fresh meta load.
108
     */
109
    static volatile Long loadedNanopubCount = null;
6 ✔
110

111
    /**
112
     * Cached checksum of nanopubs ever loaded into the {@code meta} repo.
113
     * Maintained for {@link MainVerticle}'s
114
     * {@code Nanopub-Query-Loaded-Nanopub-Checksum} response header. Mirrors the
115
     * persisted {@code npa:hasNanopubChecksum} triple that {@link #loadNanopubToRepo}
116
     * maintains — an order-independent XOR over the trusty URIs of all loaded
117
     * nanopubs, Base64-encoded. Sourced from {@code meta} for the same reasons
118
     * as {@link #loadedNanopubCount}; the two fields are bumped together so the
119
     * count and checksum always describe the same point in the load sequence.
120
     */
121
    static volatile String loadedNanopubChecksum = null;
6 ✔
122

123
    /**
124
     * Retry budget for the five (with #71 merged: six) structurally identical
125
     * retry loops in this file. Previously the shape was flat {@code 10 s × 30} —
126
     * five minutes of constant hammering at RDF4J that did not help a slow server.
127
     * The new shape is bounded exponential backoff with ±50 % jitter:
128
     * {@code base = 1, 2, 4, 8, 16, 32, 60, 60 s} for attempts 1…8, each perturbed
129
     * by up to half its base value. Jitter prevents the 4-thread loadingPool from
130
     * retrying in lock-step after a shared RDF4J failure (GC pause / overload spike).
131
     * Worst-case wall time per failing task drops from ~35 min (post-change-1
132
     * timeouts × 30 flat retries) to ~11 min (8 retries × 60 s timeout + backoff
133
     * sleeps). This is the figure that sets the circuit-breaker trip time in
134
     * {@link JellyNanopubLoader}.
135
     */
136
    private static final int MAX_RETRIES = 8;
137
    private static final long[] BACKOFF_BASE_MS =
105 ✔
138
            {1_000L, 2_000L, 4_000L, 8_000L, 16_000L, 32_000L, 60_000L, 60_000L};
139

140
    /**
141
     * Returns the sleep delay in ms for the given 1-indexed retry attempt. Delay
142
     * is {@link #BACKOFF_BASE_MS}{@code [attempt-1]} perturbed by ±50 % uniform
143
     * jitter, clamped to be non-negative.
144
     *
145
     * @param attempt 1-indexed retry attempt number
146
     * @return the computed sleep delay in ms
147
     */
148
    static long computeBackoffMillis(int attempt) {
149
        long base = BACKOFF_BASE_MS[Math.min(attempt - 1, BACKOFF_BASE_MS.length - 1)];
×
150
        long jitter = ThreadLocalRandom.current().nextLong(base + 1) - base / 2;
×
151
        return Math.max(0L, base + jitter);
×
152
    }
153

154
    private Nanopub np;
155
    private NanopubSignatureElement el = null;
9 ✔
156
    private List<Statement> metaStatements = new ArrayList<>();
15 ✔
157
    private List<Statement> nanopubStatements = new ArrayList<>();
15 ✔
158
    private List<Statement> literalStatements = new ArrayList<>();
15 ✔
159
    private List<Statement> invalidateStatements = new ArrayList<>();
15 ✔
160
    private List<Statement> textStatements, allStatements, invalidatingStatements;
161
    private List<Statement> spaceExtractionStatements = new ArrayList<>();
15 ✔
162
    private Calendar timestamp = null;
9 ✔
163
    private Statement pubkeyStatement, pubkeyStatementX;
164
    private List<String> notes = new ArrayList<>();
15 ✔
165
    private boolean aborted = false;
9 ✔
166
    private static final Logger logger = LoggerFactory.getLogger(NanopubLoader.class);
9 ✔
167

168

169
    NanopubLoader(Nanopub np, long counter) {
6 ✔
170
        this.np = np;
9 ✔
171
        if (counter >= 0) {
12 ✔
172
            logger.info("Loading nanopub #{}: <{}>", counter, np.getUri());
24 ✔
173
        } else {
174
            logger.info("Loading nanopub: <{}>", np.getUri());
15 ✔
175
        }
176

177
        // TODO Ensure proper synchronization and DB rollbacks
178

179
        // TODO Check for null characters ("\0"), which can cause problems in Virtuoso.
180

181
        String ac = TrustyUriUtils.getArtifactCode(np.getUri().toString());
15 ✔
182
        if (!np.getHeadUri().toString().contains(ac) || !np.getAssertionUri().toString().contains(ac) || !np.getProvenanceUri().toString().contains(ac) || !np.getPubinfoUri().toString().contains(ac)) {
72 !
183
            notes.add("could not load nanopub as not all graphs contained the artifact code");
×
184
            aborted = true;
×
185
            return;
×
186
        }
187

188
        // Checked before the signature: protection is about not distributing the
189
        // content at all, so it applies to invalidly-signed nanopubs too.
190
        if (NanopubServerUtils.isProtectedNanopub(np) && !FeatureFlags.localInstance()) {
15 ✔
191
            notes.add("could not load nanopub as it is protected (npx:ProtectedNanopub) and this is not a local instance");
15 ✔
192
            aborted = true;
9 ✔
193
            return;
3 ✔
194
        }
195

196
        try {
197
            el = SignatureUtils.getSignatureElement(np);
12 ✔
198
        } catch (MalformedCryptoElementException ex) {
×
199
            notes.add("Signature error");
×
200
        }
3 ✔
201
        if (!hasValidSignature(el)) {
12 ✔
202
            // Audit trail for the silent-false path: without this, an aborted nanopub
203
            // is invisible in the admin repo and only detectable as a gap between the
204
            // stream counter and the loaded count. See issue around RDF4J-instability
205
            // load gaps (full vs registry, meta vs full) where signature validation
206
            // returned false but no GeneralSecurityException was thrown.
207
            if (notes.isEmpty()) {
12 !
208
                notes.add("Invalid signature");
15 ✔
209
            }
210
            aborted = true;
9 ✔
211
            return;
3 ✔
212
        }
213

214
        pubkeyStatement = vf.createStatement(np.getUri(), NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY, vf.createLiteral(el.getPublicKeyString()), NPA.GRAPH);
39 ✔
215
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasValidSignatureForPublicKey, FULL_PUBKEY, npa:graph, meta, full pubkey if signature is valid
216
        metaStatements.add(pubkeyStatement);
18 ✔
217
        pubkeyStatementX = vf.createStatement(np.getUri(), NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY_HASH, vf.createLiteral(Utils.createHash(el.getPublicKeyString())), NPA.GRAPH);
42 ✔
218
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasValidSignatureForPublicKeyHash, PUBKEY_HASH, npa:graph, meta, hex-encoded SHA256 hash if signature is valid
219
        metaStatements.add(pubkeyStatementX);
18 ✔
220

221
        if (el.getSigners().size() == 1) {  // > 1 is deprecated
18 !
222
            metaStatements.add(vf.createStatement(np.getUri(), NPX.SIGNED_BY, el.getSigners().iterator().next(), NPA.GRAPH));
48 ✔
223
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:signedBy, SIGNER, npa:graph, meta, ID of signer
224
        }
225

226
        Set<IRI> subIris = new HashSet<>();
12 ✔
227
        Set<IRI> otherNps = new HashSet<>();
12 ✔
228
        Set<IRI> invalidated = new HashSet<>();
12 ✔
229
        Set<IRI> retracted = new HashSet<>();
12 ✔
230
        Set<IRI> superseded = new HashSet<>();
12 ✔
231
        String combinedLiterals = "";
6 ✔
232
        for (Statement st : NanopubUtils.getStatements(np)) {
33 ✔
233
            nanopubStatements.add(st);
15 ✔
234

235
            if (st.getPredicate().toString().contains(ac)) {
18 !
236
                subIris.add(st.getPredicate());
×
237
            } else {
238
                IRI b = getBaseTrustyUri(st.getPredicate());
12 ✔
239
                if (b != null) {
6 !
240
                    otherNps.add(b);
×
241
                }
242
            }
243
            if (st.getPredicate().equals(NPX.RETRACTS) && st.getObject() instanceof IRI) {
15 !
244
                retracted.add((IRI) st.getObject());
×
245
            }
246
            if (st.getPredicate().equals(NPX.INVALIDATES) && st.getObject() instanceof IRI) {
15 !
247
                invalidated.add((IRI) st.getObject());
×
248
            }
249
            if (st.getSubject().equals(np.getUri()) && st.getObject() instanceof IRI) {
30 ✔
250
                if (st.getPredicate().equals(NPX.SUPERSEDES)) {
15 ✔
251
                    superseded.add((IRI) st.getObject());
18 ✔
252
                }
253
                if (st.getObject().toString().matches(".*[^A-Za-z0-9\\-_]RA[A-Za-z0-9\\-_]{43}")) {
18 ✔
254
                    metaStatements.add(vf.createStatement(np.getUri(), st.getPredicate(), st.getObject(), NPA.NETWORK_GRAPH));
39 ✔
255
                    // @ADMIN-TRIPLE-TABLE@ NANOPUB1, RELATION, NANOPUB2, npa:networkGraph, meta, any inter-nanopub relation found in NANOPUB1
256
                }
257
                if (st.getContext().equals(np.getPubinfoUri())) {
18 ✔
258
                    if (st.getPredicate().equals(NPX.INTRODUCES) || st.getPredicate().equals(NPX.DESCRIBES) || st.getPredicate().equals(NPX.EMBEDS)) {
45 !
259
                        metaStatements.add(vf.createStatement(np.getUri(), st.getPredicate(), st.getObject(), NPA.GRAPH));
39 ✔
260
                        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:introduces, THING, npa:graph, meta, when such a triple is present in pubinfo of NANOPUB
261
                        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:describes, THING, npa:graph, meta, when such a triple is present in pubinfo of NANOPUB
262
                        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:embeds, THING, npa:graph, meta, when such a triple is present in pubinfo of NANOPUB
263
                    }
264
                }
265
            }
266
            if (st.getSubject().toString().contains(ac)) {
18 ✔
267
                subIris.add((IRI) st.getSubject());
21 ✔
268
            } else {
269
                IRI b = getBaseTrustyUri(st.getSubject());
12 ✔
270
                if (b != null) {
6 !
271
                    otherNps.add(b);
×
272
                }
273
            }
274
            if (st.getObject() instanceof IRI) {
12 ✔
275
                if (st.getObject().toString().contains(ac)) {
18 ✔
276
                    subIris.add((IRI) st.getObject());
21 ✔
277
                } else {
278
                    IRI b = getBaseTrustyUri(st.getObject());
12 ✔
279
                    if (b != null) {
6 ✔
280
                        otherNps.add(b);
12 ✔
281
                    }
282
                }
3 ✔
283
            } else {
284
                combinedLiterals += st.getObject().stringValue().replaceAll("\\s+", " ") + "\n";
27 ✔
285
//                                if (st.getSubject().equals(np.getUri()) && !st.getSubject().equals(HAS_FILTER_LITERAL)) {
286
//                                        literalStatements.add(vf.createStatement(np.getUri(), st.getPredicate(), st.getObject(), LITERAL_GRAPH));
287
//                                } else {
288
//                                        literalStatements.add(vf.createStatement(np.getUri(), HAS_LITERAL, st.getObject(), LITERAL_GRAPH));
289
//                                }
290
            }
291
        }
3 ✔
292
        subIris.remove(np.getUri());
15 ✔
293
        subIris.remove(np.getAssertionUri());
15 ✔
294
        subIris.remove(np.getProvenanceUri());
15 ✔
295
        subIris.remove(np.getPubinfoUri());
15 ✔
296
        for (IRI i : subIris) {
30 ✔
297
            metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_SUB_IRI, i, NPA.GRAPH));
33 ✔
298
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasSubIri, SUB_IRI, npa:graph, meta, for any IRI minted in the namespace of the NANOPUB
299
        }
3 ✔
300
        for (IRI i : otherNps) {
30 ✔
301
            metaStatements.add(vf.createStatement(np.getUri(), NPA.REFERS_TO_NANOPUB, i, NPA.NETWORK_GRAPH));
33 ✔
302
            // @ADMIN-TRIPLE-TABLE@ NANOPUB1, npa:refersToNanopub, NANOPUB2, npa:networkGraph, meta, generic inter-nanopub relation
303
        }
3 ✔
304
        for (IRI i : invalidated) {
18 !
305
            invalidateStatements.add(vf.createStatement(np.getUri(), NPX.INVALIDATES, i, NPA.GRAPH));
×
306
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:invalidates, INVALIDATED_NANOPUB, npa:graph, meta, if the NANOPUB retracts or supersedes another nanopub
307
        }
×
308
        for (IRI i : retracted) {
18 !
309
            invalidateStatements.add(vf.createStatement(np.getUri(), NPX.INVALIDATES, i, NPA.GRAPH));
×
310
            metaStatements.add(vf.createStatement(np.getUri(), NPX.RETRACTS, i, NPA.GRAPH));
×
311
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:retracts, RETRACTED_NANOPUB, npa:graph, meta, if the NANOPUB retracts another nanopub
312
        }
×
313
        for (IRI i : superseded) {
30 ✔
314
            invalidateStatements.add(vf.createStatement(np.getUri(), NPX.INVALIDATES, i, NPA.GRAPH));
33 ✔
315
            metaStatements.add(vf.createStatement(np.getUri(), NPX.SUPERSEDES, i, NPA.GRAPH));
33 ✔
316
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:supersedes, SUPERSEDED_NANOPUB, npa:graph, meta, if the NANOPUB supersedes another nanopub
317
        }
3 ✔
318

319
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_HEAD_GRAPH, np.getHeadUri(), NPA.GRAPH));
36 ✔
320
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasHeadGraph, HEAD_GRAPH, npa:graph, meta, direct link to the head graph of the NANOPUB
321
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_GRAPH, np.getHeadUri(), NPA.GRAPH));
36 ✔
322
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasGraph, GRAPH, npa:graph, meta, generic link to all four graphs of the given NANOPUB
323
        metaStatements.add(vf.createStatement(np.getUri(), NP.HAS_ASSERTION, np.getAssertionUri(), NPA.GRAPH));
36 ✔
324
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, np:hasAssertion, ASSERTION_GRAPH, npa:graph, meta, direct link to the assertion graph of the NANOPUB
325
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_GRAPH, np.getAssertionUri(), NPA.GRAPH));
36 ✔
326
        metaStatements.add(vf.createStatement(np.getUri(), NP.HAS_PROVENANCE, np.getProvenanceUri(), NPA.GRAPH));
36 ✔
327
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, np:hasProvenance, PROVENANCE_GRAPH, npa:graph, meta, direct link to the provenance graph of the NANOPUB
328
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_GRAPH, np.getProvenanceUri(), NPA.GRAPH));
36 ✔
329
        metaStatements.add(vf.createStatement(np.getUri(), NP.HAS_PUBINFO, np.getPubinfoUri(), NPA.GRAPH));
36 ✔
330
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, np:hasPublicationInfo, PUBINFO_GRAPH, npa:graph, meta, direct link to the pubinfo graph of the NANOPUB
331
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_GRAPH, np.getPubinfoUri(), NPA.GRAPH));
36 ✔
332

333
        String artifactCode = TrustyUriUtils.getArtifactCode(np.getUri().stringValue());
15 ✔
334
        metaStatements.add(vf.createStatement(np.getUri(), NPA.ARTIFACT_CODE, vf.createLiteral(artifactCode), NPA.GRAPH));
39 ✔
335
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:artifactCode, ARTIFACT_CODE, npa:graph, meta, artifact code starting with 'RA...'
336

337
        if (isIntroNanopub(np)) {
9 ✔
338
            IntroNanopub introNp = new IntroNanopub(np);
15 ✔
339
            metaStatements.add(vf.createStatement(np.getUri(), NPA.IS_INTRODUCTION_OF, introNp.getUser(), NPA.GRAPH));
36 ✔
340
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:isIntroductionOf, AGENT, npa:graph, meta, linking intro nanopub to the agent it is introducing
341
            for (KeyDeclaration kc : introNp.getKeyDeclarations()) {
33 ✔
342
                metaStatements.add(vf.createStatement(np.getUri(), NPA.DECLARES_PUBKEY, vf.createLiteral(kc.getPublicKeyString()), NPA.GRAPH));
42 ✔
343
                // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:declaresPubkey, FULL_PUBKEY, npa:graph, meta, full pubkey declared by the given intro NANOPUB
344
            }
3 ✔
345
        }
346

347
        try {
348
            timestamp = SimpleTimestampPattern.getCreationTime(np);
12 ✔
349
        } catch (IllegalArgumentException ex) {
×
350
            notes.add("Illegal date/time");
×
351
        }
3 ✔
352
        if (timestamp != null) {
9 !
353
            metaStatements.add(vf.createStatement(np.getUri(), DCTERMS.CREATED, vf.createLiteral(timestamp.getTime()), NPA.GRAPH));
45 ✔
354
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, dct:created, CREATION_DATE, npa:graph, meta, normalized creation timestamp
355
        }
356

357
        String literalFilter = "_pubkey_" + Utils.createHash(el.getPublicKeyString());
18 ✔
358
        for (IRI typeIri : NanopubUtils.getTypes(np)) {
33 ✔
359
            metaStatements.add(vf.createStatement(np.getUri(), NPX.HAS_NANOPUB_TYPE, typeIri, NPA.GRAPH));
33 ✔
360
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:hasNanopubType, NANOPUB_TYPE, npa:graph, meta, type of NANOPUB
361
            literalFilter += " _type_" + Utils.createHash(typeIri);
15 ✔
362
        }
3 ✔
363
        String label = NanopubUtils.getLabel(np);
9 ✔
364
        if (label != null) {
6 !
365
            metaStatements.add(vf.createStatement(np.getUri(), RDFS.LABEL, vf.createLiteral(label), NPA.GRAPH));
39 ✔
366
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, rdfs:label, LABEL, npa:graph, meta, label of NANOPUB
367
        }
368
        String description = NanopubUtils.getDescription(np);
9 ✔
369
        if (description != null) {
6 ✔
370
            metaStatements.add(vf.createStatement(np.getUri(), DCTERMS.DESCRIPTION, vf.createLiteral(description), NPA.GRAPH));
39 ✔
371
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, dct:description, LABEL, npa:graph, meta, description of NANOPUB
372
        }
373
        for (IRI creatorIri : SimpleCreatorPattern.getCreators(np)) {
33 ✔
374
            metaStatements.add(vf.createStatement(np.getUri(), DCTERMS.CREATOR, creatorIri, NPA.GRAPH));
33 ✔
375
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, dct:creator, CREATOR, npa:graph, meta, creator of NANOPUB (can be several)
376
        }
3 ✔
377
        for (IRI authorIri : SimpleCreatorPattern.getAuthors(np)) {
21 !
378
            metaStatements.add(vf.createStatement(np.getUri(), PAV.AUTHORED_BY, authorIri, NPA.GRAPH));
×
379
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, pav:authoredBy, AUTHOR, npa:graph, meta, author of NANOPUB (can be several)
380
        }
×
381

382
        if (!combinedLiterals.isEmpty()) {
9 !
383
            literalStatements.add(vf.createStatement(np.getUri(), NPA.HAS_FILTER_LITERAL, vf.createLiteral(literalFilter + "\n" + combinedLiterals), NPA.GRAPH));
45 ✔
384
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasFilterLiteral, FILTER_LITERAL, npa:graph, literal, auxiliary literal for filtering by type and pubkey in text repo
385
        }
386

387
        // Any statements that express that the currently processed nanopub is already invalidated:
388
        invalidatingStatements = getInvalidatingStatements(np.getUri());
15 ✔
389

390
        metaStatements.addAll(invalidateStatements);
18 ✔
391

392
        allStatements = new ArrayList<>(nanopubStatements);
21 ✔
393
        allStatements.addAll(metaStatements);
18 ✔
394
        allStatements.addAll(invalidatingStatements);
18 ✔
395

396
        textStatements = new ArrayList<>(literalStatements);
21 ✔
397
        textStatements.addAll(metaStatements);
18 ✔
398
        textStatements.addAll(invalidatingStatements);
18 ✔
399

400
        if (FeatureFlags.spacesEnabled()) {
6 !
401
            IRI signedBy = (el.getSigners().size() == 1) ? el.getSigners().iterator().next() : null;
42 !
402
            String pubkeyHash = Utils.createHash(el.getPublicKeyString());
15 ✔
403
            Date createdAt = (timestamp != null) ? timestamp.getTime() : null;
24 !
404
            SpacesExtractor.Context ctx = new SpacesExtractor.Context(ac, signedBy, pubkeyHash, createdAt);
24 ✔
405
            spaceExtractionStatements = SpacesExtractor.extract(np, ctx);
15 ✔
406
        }
407
    }
3 ✔
408

409
    /**
410
     * Get the HTTP client used for fetching nanopublications.
411
     *
412
     * @return the HTTP client
413
     */
414
    static HttpClient getHttpClient() {
415
        if (httpClient == null) {
6 ✔
416
            httpClient = HttpClientBuilder.create().setDefaultRequestConfig(Utils.getHttpRequestConfig()).build();
15 ✔
417
        }
418
        return httpClient;
6 ✔
419
    }
420

421
    /**
422
     * Load the given nanopublication into the database.
423
     *
424
     * @param nanopubUri Nanopublication identifier (URI)
425
     */
426
    public static void load(String nanopubUri) {
427
        if (isNanopubLoaded(nanopubUri)) {
9 !
428
            logger.info("Skipping already-loaded nanopub: <{}>", nanopubUri);
×
429
        } else {
430
            Nanopub np = GetNanopub.get(nanopubUri, getHttpClient());
12 ✔
431
            load(np, -1);
9 ✔
432
        }
433
    }
3 ✔
434

435
    /**
436
     * Load a nanopub into the database.
437
     *
438
     * @param np      the nanopub to load
439
     * @param counter the load counter, only used for logging (or -1 if not known)
440
     * @throws RDF4JException if the loading fails
441
     */
442
    public static void load(Nanopub np, long counter) throws RDF4JException {
443
        NanopubLoader loader = new NanopubLoader(np, counter);
18 ✔
444
        loader.executeLoading();
6 ✔
445
    }
3 ✔
446

447
    boolean isAborted() {
448
        return aborted;
9 ✔
449
    }
450

451
    List<String> getNotes() {
452
        return notes;
9 ✔
453
    }
454

455
    @GeneratedFlagForDependentElements
456
    private void executeLoading() {
457
        var runningTasks = new ArrayList<Future<?>>();
458
        Consumer<Runnable> runTask = t -> runningTasks.add(loadingPool.submit(t));
×
459

460
        for (String note : notes) {
461
            loadNoteToRepo(np.getUri(), note);
462
        }
463

464
        if (!aborted) {
465
            // Submit all tasks except the "meta" task
466
            if (timestamp != null) {
467
                if (new Date().getTime() - timestamp.getTimeInMillis() < THIRTY_DAYS) {
468
                    if (FeatureFlags.last30dRepoEnabled()) {
469
                        runTask.accept(() -> loadNanopubToLatest(np.getUri(), allStatements));
×
470
                    }
471
                }
472
            }
473

474
            if (FeatureFlags.textRepoEnabled()) {
475
                runTask.accept(() -> loadNanopubToRepo(np.getUri(), textStatements, "text"));
×
476
            }
477
            if (FeatureFlags.fullRepoEnabled()) {
478
                runTask.accept(() -> loadNanopubToRepo(np.getUri(), allStatements, "full"));
×
479
            }
480
            // Note: "meta" task is deferred until all other tasks complete successfully
481

482
            runTask.accept(() -> loadNanopubToRepo(np.getUri(), allStatements, "pubkey_" + Utils.createHash(el.getPublicKeyString())));
×
483
            //                loadNanopubToRepo(np.getUri(), textStatements, "text-pubkey_" + Utils.createHash(el.getPublicKeyString()));
484
            for (IRI typeIri : NanopubUtils.getTypes(np)) {
485
                // Exclude locally minted IRIs:
486
                if (typeIri.stringValue().startsWith(np.getUri().stringValue())) {
487
                    continue;
488
                }
489
                if (!typeIri.stringValue().matches("https?://.*")) {
490
                    continue;
491
                }
492
                runTask.accept(() -> loadNanopubToRepo(np.getUri(), allStatements, "type_" + Utils.createHash(typeIri)));
×
493
                //                        loadNanopubToRepo(np.getUri(), textStatements, "text-type_" + Utils.createHash(typeIri));
494
            }
495
            //                for (IRI creatorIri : SimpleCreatorPattern.getCreators(np)) {
496
            //                        // Exclude locally minted IRIs:
497
            //                        if (creatorIri.stringValue().startsWith(np.getUri().stringValue())) continue;
498
            //                        if (!creatorIri.stringValue().matches("https?://.*")) continue;
499
            //                        loadNanopubToRepo(np.getUri(), allStatements, "user_" + Utils.createHash(creatorIri));
500
            //                        loadNanopubToRepo(np.getUri(), textStatements, "text-user_" + Utils.createHash(creatorIri));
501
            //                }
502
            //                for (IRI authorIri : SimpleCreatorPattern.getAuthors(np)) {
503
            //                        // Exclude locally minted IRIs:
504
            //                        if (authorIri.stringValue().startsWith(np.getUri().stringValue())) continue;
505
            //                        if (!authorIri.stringValue().matches("https?://.*")) continue;
506
            //                        loadNanopubToRepo(np.getUri(), allStatements, "user_" + Utils.createHash(authorIri));
507
            //                        loadNanopubToRepo(np.getUri(), textStatements, "text-user_" + Utils.createHash(authorIri));
508
            //                }
509

510
            // Write to the spaces repo only when the nanopub carries its own space-relevant
511
            // extractions. Invalidators of space-relevant nanopubs are propagated to spaces
512
            // symmetrically below (forward path in loadInvalidateStatements, reverse path in
513
            // the invalidatorPubkeys block) — mirrors the per-type-repo propagation added in
514
            // PR #103 (commit 09eeb32). The materialiser's invalidation joins
515
            // (?invNp npx:invalidates ?np + ?invNp npa:hasLoadNumber ?ln in the spaces repo's
516
            // npa:graph) stay populated because the invalidators that matter are exactly the
517
            // ones we propagate.
518
            boolean thisNpIsSpaceRelevant = FeatureFlags.spacesEnabled() && !spaceExtractionStatements.isEmpty();
519
            if (thisNpIsSpaceRelevant) {
520
                runTask.accept(() -> loadToSpacesRepo(np.getUri(), allStatements, spaceExtractionStatements));
×
521
            }
522

523
            for (Statement st : invalidateStatements) {
524
                runTask.accept(() -> loadInvalidateStatements(np, el.getPublicKeyString(), st, pubkeyStatement, pubkeyStatementX, allStatements));
×
525
            }
526

527
            // Reverse-order symmetry: when retractors were loaded before this nanopub,
528
            // getInvalidatingStatements (in the constructor) captured their
529
            // `npx:invalidates` markers into invalidatingStatements. Mirror what
530
            // loadInvalidateStatements does in the forward case — load each retractor's
531
            // full content into this nanopub's per-type repos (those types the
532
            // retractor doesn't itself carry), sourced from the retractor's per-pubkey
533
            // repo (the one shard guaranteed to be populated for every successfully
534
            // loaded nanopub). When this nanopub is space-relevant, additionally load
535
            // each retractor into the spaces repo so the materialiser's invalidation
536
            // join sees them regardless of load order.
537
            Map<IRI, String> invalidatorPubkeys = collectInvalidatorPubkeys(invalidatingStatements);
538
            if (!invalidatorPubkeys.isEmpty()) {
539
                Set<IRI> thisNpTypes = NanopubUtils.getTypes(np);
540
                for (Map.Entry<IRI, String> e : invalidatorPubkeys.entrySet()) {
541
                    IRI invIri = e.getKey();
542
                    String invPubkey = e.getValue();
543
                    runTask.accept(() -> loadInvalidatorIntoTypeRepos(invIri, invPubkey, np.getUri(), thisNpTypes));
×
544
                    if (thisNpIsSpaceRelevant) {
545
                        runTask.accept(() -> loadInvalidatorIntoSpacesRepo(invIri, invPubkey, np.getUri()));
×
546
                    }
547
                }
548
            }
549

550
            // Wait for all non-meta tasks to complete successfully before submitting the meta task.
551
            // On failure, cancel the remaining futures so orphaned tasks don't keep running in the
552
            // shared loadingPool and race with the next batch retry (which re-submits the same
553
            // nanopub against the same repos).
554
            for (var task : runningTasks) {
555
                try {
556
                    task.get();
557
                } catch (ExecutionException | InterruptedException ex) {
558
                    for (var t : runningTasks) {
559
                        if (!t.isDone()) {
560
                            t.cancel(true);
561
                        }
562
                    }
563
                    throw new RuntimeException("Error in nanopub loading thread", ex.getCause());
564
                }
565
            }
566

567
            // Now submit and wait for the "meta" task after all other tasks have completed successfully
568
            Future<?> metaTask = loadingPool.submit(() -> loadNanopubToRepo(np.getUri(), metaStatements, "meta"));
×
569
            try {
570
                metaTask.get();
571
            } catch (ExecutionException | InterruptedException ex) {
572
                throw new RuntimeException("Error in nanopub loading thread (meta task)", ex.getCause());
573
            }
574
        }
575
    }
576

577
    private static Long lastUpdateOfLatestRepo = null;
6 ✔
578
    private static long THIRTY_DAYS = 1000L * 60 * 60 * 24 * 30;
6 ✔
579
    private static long ONE_HOUR = 1000L * 60 * 60;
6 ✔
580

581
    @GeneratedFlagForDependentElements
582
    private static void loadNanopubToLatest(IRI npId, List<Statement> statements) {
583
        boolean success = false;
584
        int retries = 0;
585
        while (!success) {
586
            RepositoryConnection conn = TripleStore.get().getRepoConnection("last30d");
587
            try (conn) {
588
                // Read committed, because deleting old nanopubs is idempotent. Inserts do not collide
589
                // with deletes, because we are not inserting old nanopubs.
590
                conn.begin(IsolationLevels.READ_COMMITTED);
591
                conn.add(statements);
592
                if (lastUpdateOfLatestRepo == null || new Date().getTime() - lastUpdateOfLatestRepo > ONE_HOUR) {
593
                    logger.debug("Pruning nanopubs older than 30 days from last30d repo...");
594
                    Literal thirtyDaysAgo = vf.createLiteral(new Date(new Date().getTime() - THIRTY_DAYS));
595
                    TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT * { graph <" + NPA.GRAPH + "> { " + "?np <" + DCTERMS.CREATED + "> ?date . " + "filter ( ?date < ?thirtydaysago ) " + "} }");
596
                    q.setBinding("thirtydaysago", thirtyDaysAgo);
597
                    try (TupleQueryResult r = q.evaluate()) {
598
                        while (r.hasNext()) {
599
                            BindingSet b = r.next();
600
                            IRI oldNpId = (IRI) b.getBinding("np").getValue();
601
                            logger.debug("Pruning expired nanopub from last30d repo: <{}>", oldNpId);
602
                            for (Value v : Utils.getObjectsForPattern(conn, NPA.GRAPH, oldNpId, NPA.HAS_GRAPH)) {
603
                                // Remove all four nanopub graphs:
604
                                conn.remove((Resource) null, (IRI) null, (Value) null, (IRI) v);
605
                            }
606
                            // Remove nanopubs in admin graphs:
607
                            conn.remove(oldNpId, null, null, NPA.GRAPH);
608
                            conn.remove(oldNpId, null, null, NPA.NETWORK_GRAPH);
609
                        }
610
                    }
611
                    lastUpdateOfLatestRepo = new Date().getTime();
612
                }
613
                conn.commit();
614
                success = true;
615
            } catch (Exception ex) {
616
                logger.warn("Failed to load nanopub <{}> to last30d repo: {}", npId, ex.getMessage(), ex);
617
                if (conn.isActive()) {
618
                    conn.rollback();
619
                }
620
            }
621
            if (!success) {
622
                retries++;
623
                if (retries >= MAX_RETRIES) {
624
                    throw new RuntimeException("Failed to load nanopub " + npId + " to last30d repo after " + MAX_RETRIES + " retries");
625
                }
626
                long delay = computeBackoffMillis(retries);
627
                logger.info("Retrying load of <{}> to last30d repo in {} ms (attempt {}/{})...", npId, delay, retries, MAX_RETRIES);
628
                try {
629
                    Thread.sleep(delay);
630
                } catch (InterruptedException x) {
631
                    Thread.currentThread().interrupt();
632
                }
633
            }
634
        }
635
    }
636

637
    @GeneratedFlagForDependentElements
638
    private static void loadNanopubToRepo(IRI npId, List<Statement> statements, String repoName) {
639
        boolean success = false;
640
        int retries = 0;
641
        while (!success) {
642
            // The count/checksum chain must not suffer write skew, so this read-modify-write
643
            // is serialised — by repoWriteLock rather than by a SERIALIZABLE transaction. This
644
            // process is the only writer of those triples, so the guarantee is the same; see
645
            // repoWriteLocks for why the isolation level is the expensive way to buy it.
646
            // Held across the whole transaction, released before any retry back-off.
647
            ReentrantLock repoLock = repoWriteLock(repoName);
648
            repoLock.lock();
649
            try {
650
                RepositoryConnection conn = TripleStore.get().getRepoConnection(repoName);
651
                long newCountForCache = -1;
652
                String newChecksumForCache = null;
653
                try (conn) {
654
                    conn.begin(IsolationLevels.SNAPSHOT);
655
                    var repoStatus = fetchRepoStatus(conn, npId, repoName);
656
                    if (repoStatus.isLoaded) {
657
                        // INFO, not DEBUG: this skip decides that a shard write is unnecessary
658
                        // based on a single store read. When the backend misbehaves (issue #139:
659
                        // a shard "successfully" written yet not durable), this line is the only
660
                        // trace distinguishing a false skip from a lost commit.
661
                        logger.info("Skipping already-loaded nanopub <{}> in repo '{}'", npId, repoName);
662
                    } else {
663
                        String newChecksum = NanopubUtils.updateXorChecksum(npId, repoStatus.checksum);
664
                        conn.remove(NPA.THIS_REPO, NPA.HAS_NANOPUB_COUNT, null, NPA.GRAPH);
665
                        conn.remove(NPA.THIS_REPO, NPA.HAS_NANOPUB_CHECKSUM, null, NPA.GRAPH);
666
                        conn.add(NPA.THIS_REPO, NPA.HAS_NANOPUB_COUNT, vf.createLiteral(repoStatus.count + 1), NPA.GRAPH);
667
                        // @ADMIN-TRIPLE-TABLE@ REPO, npa:hasNanopubCount, NANOPUB_COUNT, npa:graph, admin, number of nanopubs loaded
668
                        conn.add(NPA.THIS_REPO, NPA.HAS_NANOPUB_CHECKSUM, vf.createLiteral(newChecksum), NPA.GRAPH);
669
                        // @ADMIN-TRIPLE-TABLE@ REPO, npa:hasNanopubChecksum, NANOPUB_CHECKSUM, npa:graph, admin, checksum of all loaded nanopubs (order-independent XOR checksum on trusty URIs in Base64 notation)
670
                        conn.add(npId, NPA.HAS_LOAD_NUMBER, vf.createLiteral(repoStatus.count), NPA.GRAPH);
671
                        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasLoadNumber, LOAD_NUMBER, npa:graph, admin, the sequential number at which this NANOPUB was loaded
672
                        conn.add(npId, NPA.HAS_LOAD_CHECKSUM, vf.createLiteral(newChecksum), NPA.GRAPH);
673
                        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasLoadChecksum, LOAD_CHECKSUM, npa:graph, admin, the checksum of all loaded nanopubs after loading the given NANOPUB
674
                        conn.add(npId, NPA.HAS_LOAD_TIMESTAMP, vf.createLiteral(new Date()), NPA.GRAPH);
675
                        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasLoadTimestamp, LOAD_TIMESTAMP, npa:graph, admin, the time point at which this NANOPUB was loaded
676
                        conn.add(statements);
677
                        if ("meta".equals(repoName)) {
678
                            newCountForCache = repoStatus.count + 1;
679
                            newChecksumForCache = newChecksum;
680
                        }
681
                    }
682
                    conn.commit();
683
                    if (newCountForCache >= 0) {
684
                        loadedNanopubCount = newCountForCache;
685
                    }
686
                    if (newChecksumForCache != null) {
687
                        loadedNanopubChecksum = newChecksumForCache;
688
                    }
689
                    success = true;
690
                } catch (Exception ex) {
691
                    logger.warn("Failed to load nanopub <{}> to repo '{}': {}", npId, repoName, ex.getMessage(), ex);
692
                    if (conn.isActive()) {
693
                        conn.rollback();
694
                    }
695
                }
696
            } finally {
697
                repoLock.unlock();
698
            }
699
            if (!success) {
700
                retries++;
701
                if (retries >= MAX_RETRIES) {
702
                    throw new RuntimeException("Failed to load nanopub " + npId + " to repo " + repoName + " after " + MAX_RETRIES + " retries");
703
                }
704
                long delay = computeBackoffMillis(retries);
705
                logger.info("Retrying load of <{}> to repo '{}' in {} ms (attempt {}/{})...", npId, repoName, delay, retries, MAX_RETRIES);
706
                try {
707
                    Thread.sleep(delay);
708
                } catch (InterruptedException x) {
709
                    Thread.currentThread().interrupt();
710
                }
711
            }
712
        }
713
    }
714

715
    /**
716
     * Writes the raw nanopub statements (all four graphs) into the {@code spaces}
717
     * repo alongside the pre-computed extraction statements (which target
718
     * {@code npa:spacesGraph}). Stamps the load-number on the nanopub IRI and bumps
719
     * {@code npa:thisRepo npa:currentLoadCounter} in {@code npa:graph}, all within
720
     * one serializable transaction.
721
     *
722
     * <p>Idempotent: if the nanopub already has a {@code npa:hasLoadNumber} stamp in
723
     * {@code npa:graph} of the {@code spaces} repo, this is a no-op.
724
     *
725
     * @param npId            nanopub IRI
726
     * @param nanopubTriples  raw nanopub statements (all four graphs + meta)
727
     * @param spaceExtraction summary triples destined for {@code npa:spacesGraph}
728
     */
729
    @GeneratedFlagForDependentElements
730
    private static void loadToSpacesRepo(IRI npId, List<Statement> nanopubTriples,
731
                                         List<Statement> spaceExtraction) {
732
        boolean success = false;
733
        int retries = 0;
734
        while (!success) {
735
            // Same substitution as loadNanopubToRepo: the spaces load counter is a
736
            // read-modify-write, serialised by repoWriteLock instead of by the isolation
737
            // level. The spaces branch is also written by AuthorityResolver, whose own
738
            // writers serialise via its synchronized methods at SNAPSHOT/READ_COMMITTED.
739
            ReentrantLock repoLock = repoWriteLock("spaces");
740
            repoLock.lock();
741
            try {
742
                RepositoryConnection conn = TripleStore.get().getRepoConnection("spaces");
743
                try (conn) {
744
                    conn.begin(IsolationLevels.SNAPSHOT);
745
                    // Idempotency: skip if this nanopub is already stamped in this repo.
746
                    if (Utils.getObjectForPattern(conn, NPA.GRAPH, npId, NPA.HAS_LOAD_NUMBER) != null) {
747
                        // INFO for the same reason as the loadNanopubToRepo skip (issue #139).
748
                        logger.info("Skipping already-loaded nanopub <{}> in spaces repo", npId);
749
                        conn.commit();
750
                        success = true;
751
                        continue;
752
                    }
753
                    long newCounter = fetchSpacesLoadCounter(conn) + 1;
754
                    conn.remove(NPA.THIS_REPO,
755
                            com.knowledgepixels.query.vocabulary.SpacesVocab.CURRENT_LOAD_COUNTER,
756
                            null, NPA.GRAPH);
757
                    conn.add(NPA.THIS_REPO,
758
                            com.knowledgepixels.query.vocabulary.SpacesVocab.CURRENT_LOAD_COUNTER,
759
                            vf.createLiteral(newCounter), NPA.GRAPH);
760
                    conn.add(npId, NPA.HAS_LOAD_NUMBER, vf.createLiteral(newCounter), NPA.GRAPH);
761
                    conn.add(nanopubTriples);
762
                    conn.add(spaceExtraction);
763
                    conn.commit();
764
                    success = true;
765
                } catch (Exception ex) {
766
                    logger.warn("Failed to load nanopub <{}> to spaces repo: {}", npId, ex.getMessage(), ex);
767
                    if (conn.isActive()) {
768
                        conn.rollback();
769
                    }
770
                }
771
            } finally {
772
                repoLock.unlock();
773
            }
774
            if (!success) {
775
                retries++;
776
                if (retries >= MAX_RETRIES) {
777
                    throw new RuntimeException("Failed to load nanopub " + npId + " to spaces repo after " + MAX_RETRIES + " retries");
778
                }
779
                long delay = computeBackoffMillis(retries);
780
                logger.info("Retrying load of <{}> to spaces repo in {} ms (attempt {}/{})...", npId, delay, retries, MAX_RETRIES);
781
                try {
782
                    Thread.sleep(delay);
783
                } catch (InterruptedException x) {
784
                    Thread.currentThread().interrupt();
785
                }
786
            }
787
        }
788
    }
789

790
    /**
791
     * Returns the cumulative count of nanopubs ever loaded into the {@code meta}
792
     * repo, or {@code null} if the value cannot be determined (e.g. the store
793
     * hasn't been initialised yet). Reads the persisted {@code npa:hasNanopubCount}
794
     * triple on first call and caches it in {@link #loadedNanopubCount};
795
     * subsequent fresh loads update the cache in-place.
796
     *
797
     * <p><b>Blocks</b> on a cold cache — use {@link #getCachedLoadedNanopubCount()}
798
     * from the event loop.
799
     */
800
    public static Long getLoadedNanopubCount() {
801
        Long v = loadedNanopubCount;
6 ✔
802
        if (v != null) {
6 ✔
803
            return v;
6 ✔
804
        }
805
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection("meta")) {
12 ✔
806
            Value val = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO, NPA.HAS_NANOPUB_COUNT);
×
807
            if (val != null) {
×
808
                v = Long.parseLong(val.stringValue());
×
809
                loadedNanopubCount = v;
×
810
                return v;
×
811
            }
812
        } catch (NumberFormatException ex) {
×
813
            logger.warn("Malformed npa:hasNanopubCount literal in meta repo (value not parseable as long): {}", ex.getMessage(), ex);
×
814
        } catch (Exception ex) {
3 ✔
815
            logger.warn("Could not read npa:hasNanopubCount from meta repo", ex);
12 ✔
816
        }
×
817
        return null;
6 ✔
818
    }
819

820
    /**
821
     * The cached loaded-nanopub count, without the store read that
822
     * {@link #getLoadedNanopubCount()} falls back to, or {@code null} if nothing has
823
     * populated it yet.
824
     *
825
     * <p>For callers that must not block — specifically
826
     * {@link MainVerticle#applyGlobalHeaders}, which runs on the Vert.x event loop
827
     * for every inbound request. The lazy fallback does blocking HTTP, and on a cold
828
     * cache (i.e. after every restart) that stalled the event loop until the store
829
     * answered; Vert.x's BlockedThreadChecker fired repeatedly on 2026-07-31. Worse,
830
     * with the store unreachable it would have blocked every request for the full
831
     * 10 s connect timeout, turning an RDF4J outage into a total outage of the HTTP
832
     * layer — including the status headers used to diagnose it.
833
     *
834
     * <p>Kept warm off the event loop by {@link #primeHeaderCaches()}.
835
     *
836
     * @return the cached count, or null if not yet known
837
     */
838
    public static Long getCachedLoadedNanopubCount() {
839
        return loadedNanopubCount;
6 ✔
840
    }
841

842
    /**
843
     * The cached loaded-nanopub checksum, without the store read that
844
     * {@link #getLoadedNanopubChecksum()} falls back to, or {@code null} if nothing
845
     * has populated it yet. Same event-loop rationale as
846
     * {@link #getCachedLoadedNanopubCount()}.
847
     *
848
     * @return the cached checksum, or null if not yet known
849
     */
850
    public static String getCachedLoadedNanopubChecksum() {
851
        return loadedNanopubChecksum;
6 ✔
852
    }
853

854
    /**
855
     * Populates the caches read by {@link #getCachedLoadedNanopubCount()} and
856
     * {@link #getCachedLoadedNanopubChecksum()}, going to the store if they are cold.
857
     *
858
     * <p>Both values are otherwise only refreshed when a nanopub is actually loaded,
859
     * so an instance that starts up already caught up would never populate them and
860
     * would serve those headers empty forever. Something off the event loop has to
861
     * prime them; {@link MetricsCollector#updateMetrics()} does, on its own executor.
862
     *
863
     * <p><b>Blocks.</b> Never call from the Vert.x event loop.
864
     */
865
    public static void primeHeaderCaches() {
866
        getLoadedNanopubCount();
6 ✔
867
        getLoadedNanopubChecksum();
6 ✔
868
    }
3 ✔
869

870
    /**
871
     * Returns the order-independent XOR checksum (Base64-encoded) of trusty URIs
872
     * of all nanopubs ever loaded into the {@code meta} repo, or {@code null} if
873
     * the value cannot be determined (e.g. the store hasn't been initialised
874
     * yet). Reads the persisted {@code npa:hasNanopubChecksum} triple on first
875
     * call and caches it in {@link #loadedNanopubChecksum}; subsequent fresh
876
     * loads update the cache in-place alongside {@link #loadedNanopubCount}.
877
     *
878
     * <p><b>Blocks</b> on a cold cache — use {@link #getCachedLoadedNanopubChecksum()}
879
     * from the event loop.
880
     */
881
    public static String getLoadedNanopubChecksum() {
882
        String v = loadedNanopubChecksum;
6 ✔
883
        if (v != null) {
6 !
884
            return v;
×
885
        }
886
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection("meta")) {
12 ✔
887
            Value val = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO, NPA.HAS_NANOPUB_CHECKSUM);
×
888
            if (val != null) {
×
889
                v = val.stringValue();
×
890
                loadedNanopubChecksum = v;
×
891
                return v;
×
892
            }
893
        } catch (Exception ex) {
3 !
894
            logger.warn("Could not read npa:hasNanopubChecksum from meta repo", ex);
12 ✔
895
        }
×
896
        return null;
6 ✔
897
    }
898

899
    private static long fetchSpacesLoadCounter(RepositoryConnection conn) {
900
        Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
901
                com.knowledgepixels.query.vocabulary.SpacesVocab.CURRENT_LOAD_COUNTER);
902
        if (v == null) {
×
903
            return 0;
×
904
        }
905
        try {
906
            return Long.parseLong(v.stringValue());
×
907
        } catch (NumberFormatException ex) {
×
908
            logger.warn("Malformed npa:currentLoadCounter literal in spaces repo (value not parseable as long): \"{}\"", v.stringValue());
×
909
            return 0;
×
910
        }
911
    }
912

913
    record RepoStatus(boolean isLoaded, long count, String checksum) {
36 ✔
914
    }
915

916
    /**
917
     * To execute before loading a nanopub: check if the nanopub is already loaded and what is the
918
     * current load counter and checksum. This effectively batches three queries into one.
919
     * This method must be called from within a transaction.
920
     *
921
     * @param conn repo connection
922
     * @param npId nanopub ID
923
     * @return the current status
924
     */
925
    @GeneratedFlagForDependentElements
926
    static RepoStatus fetchRepoStatus(RepositoryConnection conn, IRI npId, String repoName) {
927
        var result = conn.prepareTupleQuery(QueryLanguage.SPARQL, REPO_STATUS_QUERY_TEMPLATE.formatted(npId)).evaluate();
928
        try (result) {
929
            if (!result.hasNext()) {
930
                // Every repo this loader writes is seeded with count=0 + INIT_CHECKSUM in
931
                // initNewRepo's creation transaction, so an empty result can only mean a
932
                // degraded read (a misbehaving store returning no rows instead of failing,
933
                // issue #142) or a store that lost its admin triples. Treating it as "fresh
934
                // repo" would commit count=1 over the existing chain — observed on the kpxl
935
                // full repo 2026-08-12 (count reset from 86860 to ~0 while all data was
936
                // still present). Throw instead: the caller's retry loop absorbs transients,
937
                // and a persistent failure surfaces to the operator rather than corrupting
938
                // the chain.
939
                throw new RuntimeException("Repo '" + repoName + "' returned no count/checksum chain; "
940
                        + "refusing to treat a possibly-degraded read as a fresh repo");
941
            }
942
            var row = result.next();
943
            return new RepoStatus(row.hasBinding("loadNumber"), Long.parseLong(row.getBinding("count").getValue().stringValue()), row.getBinding("checksum").getValue().stringValue());
944
        }
945
    }
946

947
    @GeneratedFlagForDependentElements
948
    private static void loadInvalidateStatements(Nanopub thisNp, String thisPubkey, Statement invalidateStatement, Statement pubkeyStatement, Statement pubkeyStatementX, List<Statement> thisAllStatements) {
949
        boolean success = false;
950
        int retries = 0;
951
        List<IRI> typesToLoadFullInto = new ArrayList<>();
952
        boolean targetIsSpaceRelevant = false;
953
        while (!success) {
954
            typesToLoadFullInto.clear();
955
            targetIsSpaceRelevant = false;
956
            List<RepositoryConnection> connections = new ArrayList<>();
957
            RepositoryConnection metaConn = TripleStore.get().getRepoConnection("meta");
958
            try {
959
                IRI invalidatedNpId = (IRI) invalidateStatement.getObject();
960
                // Basic isolation because here we only read append-only data.
961
                metaConn.begin(IsolationLevels.READ_COMMITTED);
962

963
                Value pubkeyValue = Utils.getObjectForPattern(metaConn, NPA.GRAPH, invalidatedNpId, NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY);
964
                if (pubkeyValue != null) {
965
                    String pubkey = pubkeyValue.stringValue();
966

967
                    if (!pubkey.equals(thisPubkey)) {
968
                        //logger.info("Adding invalidation expressed in " + thisNp.getUri() + " also to repo for pubkey " + pubkey);
969
                        connections.add(loadStatements("pubkey_" + Utils.createHash(pubkey), invalidateStatement, pubkeyStatement, pubkeyStatementX));
970
//                                                connections.add(loadStatements("text-pubkey_" + Utils.createHash(pubkey), invalidateStatement, pubkeyStatement));
971
                    }
972

973
                    Set<IRI> thisNpTypes = NanopubUtils.getTypes(thisNp);
974
                    for (Value v : Utils.getObjectsForPattern(metaConn, NPA.GRAPH, invalidatedNpId, NPX.HAS_NANOPUB_TYPE)) {
975
                        if (v instanceof IRI typeIri) {
976
                            if (!thisNpTypes.contains(typeIri)) {
977
                                // Defer until after the meta-read commits — full load goes
978
                                // through loadNanopubToRepo, which has its own transaction
979
                                // and retry loop (see post-loop block below).
980
                                typesToLoadFullInto.add(typeIri);
981
                            }
982
                            if (SpacesExtractor.TRIGGER_TYPES.contains(typeIri)) {
983
                                // Target carries a space-relevant type — propagate the
984
                                // retractor into the spaces repo too (deferred, same
985
                                // reason as above).
986
                                targetIsSpaceRelevant = true;
987
                            }
988
                        }
989
                    }
990

991
//                                        for (Value v : Utils.getObjectsForPattern(metaConn, NPA.GRAPH, invalidatedNpId, DCTERMS.CREATOR)) {
992
//                                                IRI creatorIri = (IRI) v;
993
//                                                if (!SimpleCreatorPattern.getCreators(thisNp).contains(creatorIri)) {
994
//                                                        //logger.info("Adding invalidation expressed in " + thisNp.getUri() + " also to repo for user " + creatorIri);
995
//                                                        connections.add(loadStatements("user_" + Utils.createHash(creatorIri), invalidateStatement, pubkeyStatement));
996
//                                                        connections.add(loadStatements("text-user_" + Utils.createHash(creatorIri), invalidateStatement, pubkeyStatement));
997
//                                                }
998
//                                        }
999
                }
1000

1001
                metaConn.commit();
1002
                // TODO handle case that some commits succeed and some fail
1003
                for (RepositoryConnection c : connections) c.commit();
1004
                success = true;
1005
            } catch (Exception ex) {
1006
                logger.warn("Failed to load invalidation statements from <{}> to target repos: {}", thisNp.getUri(), ex.getMessage(), ex);
1007
                if (metaConn.isActive()) {
1008
                    metaConn.rollback();
1009
                }
1010
                for (RepositoryConnection c : connections) {
1011
                    if (c.isActive()) {
1012
                        c.rollback();
1013
                    }
1014
                }
1015
            } finally {
1016
                metaConn.close();
1017
                for (RepositoryConnection c : connections) c.close();
1018
            }
1019
            if (!success) {
1020
                retries++;
1021
                if (retries >= MAX_RETRIES) {
1022
                    throw new RuntimeException("Failed to load invalidate statements for " + thisNp.getUri() + " after " + MAX_RETRIES + " retries");
1023
                }
1024
                long delay = computeBackoffMillis(retries);
1025
                logger.info("Retrying invalidation-statement load for <{}> in {} ms (attempt {}/{})...", thisNp.getUri(), delay, retries, MAX_RETRIES);
1026
                try {
1027
                    Thread.sleep(delay);
1028
                } catch (InterruptedException x) {
1029
                    Thread.currentThread().interrupt();
1030
                }
1031
            }
1032
        }
1033
        // Mirror the Registries' behaviour: index a retraction under the types of the
1034
        // nanopub it invalidates, even when the retractor itself doesn't carry those
1035
        // types. Load the full retracting nanopub (not just the npx:invalidates marker)
1036
        // so a query against a type repo can fetch the retractor's own assertion /
1037
        // provenance / pubinfo, not only the join handle.
1038
        // loadNanopubToRepo is idempotent (early-exit on npa:hasLoadNumber) and runs
1039
        // its own locked transaction + retry loop, so it's safe to call here.
1040
        for (IRI typeIri : typesToLoadFullInto) {
1041
            loadNanopubToRepo(thisNp.getUri(), thisAllStatements, "type_" + Utils.createHash(typeIri));
1042
        }
1043
        // Same rationale for the spaces repo: when the invalidated nanopub is itself
1044
        // space-relevant, the retractor needs to land in the spaces repo so the
1045
        // materialiser's invalidation join (?invNp npx:invalidates ?np +
1046
        // ?invNp npa:hasLoadNumber ?ln in npa:graph) finds it. spaceExtractionStatements
1047
        // is empty here — the retractor is not space-relevant by itself, otherwise it
1048
        // would have already been loaded to spaces by the regular spaces-load task.
1049
        if (targetIsSpaceRelevant && FeatureFlags.spacesEnabled()) {
1050
            loadToSpacesRepo(thisNp.getUri(), thisAllStatements, Collections.emptyList());
1051
        }
1052
    }
1053

1054
    /**
1055
     * Extracts a map from invalidator IRI to that invalidator's pubkey literal
1056
     * out of an {@code invalidatingStatements} list as produced by
1057
     * {@link #getInvalidatingStatements}. The list interleaves
1058
     * {@code (?inv, npx:invalidates, ?np)} and
1059
     * {@code (?inv, npa:hasValidSignatureForPublicKey, ?pubkey)} triples per
1060
     * invalidator; this helper picks out only the pubkey-binding triples.
1061
     */
1062
    private static Map<IRI, String> collectInvalidatorPubkeys(List<Statement> invalidatingStatements) {
1063
        Map<IRI, String> result = new LinkedHashMap<>();
×
1064
        for (Statement st : invalidatingStatements) {
×
1065
            if (st.getPredicate().equals(NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY)
×
1066
                && st.getSubject() instanceof IRI invIri) {
×
1067
                result.put(invIri, st.getObject().stringValue());
×
1068
            }
1069
        }
×
1070
        return result;
×
1071
    }
1072

1073
    /**
1074
     * Reverse-order counterpart of the forward-order full-content propagation in
1075
     * {@link #loadInvalidateStatements}: when this nanopub had already-loaded
1076
     * retractors at the time of its own load (captured by
1077
     * {@link #getInvalidatingStatements}), load each retractor's full content
1078
     * into this nanopub's per-type repos — restricted to those types the
1079
     * retractor doesn't itself carry (the retractor's own load already populated
1080
     * the type repos it covers).
1081
     *
1082
     * <p>Source is the retractor's per-pubkey repo, which is the one shard
1083
     * unconditionally populated for every successfully-loaded nanopub. The
1084
     * retractor's types are read from the meta repo so we can skip type repos
1085
     * the retractor's own regular load already populated.
1086
     */
1087
    @GeneratedFlagForDependentElements
1088
    private static void loadInvalidatorIntoTypeRepos(IRI invIri, String invPubkey, IRI thisNpId, Set<IRI> thisNpTypes) {
1089
        Set<IRI> invTypes = readInvalidatorTypesFromMeta(invIri, thisNpId);
1090

1091
        List<IRI> typesToLoadInto = new ArrayList<>();
1092
        for (IRI typeIri : thisNpTypes) {
1093
            // Match the regular per-type load loop's exclusion of locally-minted IRIs.
1094
            if (typeIri.stringValue().startsWith(thisNpId.stringValue())) {
1095
                continue;
1096
            }
1097
            if (!typeIri.stringValue().matches("https?://.*")) {
1098
                continue;
1099
            }
1100
            if (!invTypes.contains(typeIri)) {
1101
                typesToLoadInto.add(typeIri);
1102
            }
1103
        }
1104
        if (typesToLoadInto.isEmpty()) {
1105
            return;
1106
        }
1107

1108
        List<Statement> invContent = fetchNanopubAllStatementsFromPubkeyRepo(invIri, invPubkey);
1109
        for (IRI typeIri : typesToLoadInto) {
1110
            loadNanopubToRepo(invIri, invContent, "type_" + Utils.createHash(typeIri));
1111
        }
1112
    }
1113

1114
    /**
1115
     * Reverse-order counterpart for the spaces repo: when a space-relevant nanopub
1116
     * is loaded and {@link #getInvalidatingStatements} captured already-loaded
1117
     * retractors of it, load each retractor's full content into the spaces repo so
1118
     * the materialiser's invalidation join (?invNp npx:invalidates ?np +
1119
     * ?invNp npa:hasLoadNumber ?ln in npa:graph) finds it regardless of the
1120
     * load order between target and retractor.
1121
     *
1122
     * <p>Source is the retractor's per-pubkey repo (the one shard unconditionally
1123
     * populated for every successfully-loaded nanopub). Passes an empty
1124
     * {@code spaceExtraction} list to {@link #loadToSpacesRepo}: by construction
1125
     * the retractor would already be in the spaces repo by its regular spaces-load
1126
     * task if it carried space-relevant extractions of its own.
1127
     * {@link #loadToSpacesRepo} is idempotent on {@code npa:hasLoadNumber}, so
1128
     * the double-load case is a no-op.
1129
     */
1130
    @GeneratedFlagForDependentElements
1131
    private static void loadInvalidatorIntoSpacesRepo(IRI invIri, String invPubkey, IRI thisNpId) {
1132
        List<Statement> invContent = fetchNanopubAllStatementsFromPubkeyRepo(invIri, invPubkey);
1133
        loadToSpacesRepo(invIri, invContent, Collections.emptyList());
1134
    }
1135

1136
    @GeneratedFlagForDependentElements
1137
    private static Set<IRI> readInvalidatorTypesFromMeta(IRI invIri, IRI thisNpId) {
1138
        Set<IRI> invTypes = new HashSet<>();
1139
        boolean success = false;
1140
        int retries = 0;
1141
        while (!success) {
1142
            invTypes.clear();
1143
            RepositoryConnection metaConn = TripleStore.get().getRepoConnection("meta");
1144
            try (metaConn) {
1145
                metaConn.begin(IsolationLevels.READ_COMMITTED);
1146
                for (Value v : Utils.getObjectsForPattern(metaConn, NPA.GRAPH, invIri, NPX.HAS_NANOPUB_TYPE)) {
1147
                    if (v instanceof IRI ti) {
1148
                        invTypes.add(ti);
1149
                    }
1150
                }
1151
                metaConn.commit();
1152
                success = true;
1153
            } catch (Exception ex) {
1154
                logger.warn("Failed to read types for invalidator <{}> (needed for target <{}>): {}", invIri, thisNpId, ex.getMessage(), ex);
1155
                if (metaConn.isActive()) {
1156
                    metaConn.rollback();
1157
                }
1158
            }
1159
            if (!success) {
1160
                retries++;
1161
                if (retries >= MAX_RETRIES) {
1162
                    throw new RuntimeException("Failed to read invalidator types for " + invIri + " after " + MAX_RETRIES + " retries");
1163
                }
1164
                long delay = computeBackoffMillis(retries);
1165
                logger.info("Retrying type-read for invalidator <{}> in {} ms (attempt {}/{})...", invIri, delay, retries, MAX_RETRIES);
1166
                try {
1167
                    Thread.sleep(delay);
1168
                } catch (InterruptedException x) {
1169
                    Thread.currentThread().interrupt();
1170
                }
1171
            }
1172
        }
1173
        return invTypes;
1174
    }
1175

1176
    /**
1177
     * Reads a nanopub's content back from its per-pubkey repo as a list of
1178
     * statements that mirrors what its original load produced into
1179
     * {@code allStatements}, minus the per-repo bookkeeping triples
1180
     * ({@code npa:hasLoadNumber}, {@code npa:hasLoadChecksum},
1181
     * {@code npa:hasLoadTimestamp}). {@link #loadNanopubToRepo} stamps those
1182
     * fresh on every destination repo, so they must be filtered out of the
1183
     * source set.
1184
     *
1185
     * <p>Fetched content:
1186
     * <ul>
1187
     *   <li>All triples in the nanopub's four named graphs, discovered via
1188
     *       {@code <npId> npa:hasGraph ?g} in {@code npa:graph}.</li>
1189
     *   <li>{@code (<npId>, ?p, ?o)} in {@code npa:graph}, excluding the per-repo
1190
     *       bookkeeping predicates above.</li>
1191
     *   <li>{@code (?inv, npx:invalidates, <npId>)} in {@code npa:graph}, plus
1192
     *       the matching {@code npa:hasValidSignatureForPublicKey[Hash]} triples
1193
     *       of each {@code ?inv}, so propagation carries the nanopub's full
1194
     *       invalidator history (which doesn't affect query results — see the
1195
     *       one-hop filter in {@code Utils#defaultQuery} — but keeps repos
1196
     *       consistent).</li>
1197
     *   <li>{@code (<npId>, ?p, ?o)} in {@code npa:networkGraph}.</li>
1198
     * </ul>
1199
     */
1200
    @GeneratedFlagForDependentElements
1201
    private static List<Statement> fetchNanopubAllStatementsFromPubkeyRepo(IRI npId, String pubkey) {
1202
        String repoName = "pubkey_" + Utils.createHash(pubkey);
1203
        boolean success = false;
1204
        int retries = 0;
1205
        List<Statement> result = new ArrayList<>();
1206
        while (!success) {
1207
            result.clear();
1208
            RepositoryConnection conn = TripleStore.get().getRepoConnection(repoName);
1209
            try (conn) {
1210
                // Append-only data + idempotent re-load downstream: READ_COMMITTED suffices.
1211
                conn.begin(IsolationLevels.READ_COMMITTED);
1212

1213
                List<IRI> npGraphs = new ArrayList<>();
1214
                try (RepositoryResult<Statement> r = conn.getStatements(npId, NPA.HAS_GRAPH, null, NPA.GRAPH)) {
1215
                    while (r.hasNext()) {
1216
                        Value o = r.next().getObject();
1217
                        if (o instanceof IRI iri) {
1218
                            npGraphs.add(iri);
1219
                        }
1220
                    }
1221
                }
1222

1223
                for (IRI g : npGraphs) {
1224
                    try (RepositoryResult<Statement> r = conn.getStatements(null, null, null, g)) {
1225
                        while (r.hasNext()) result.add(r.next());
1226
                    }
1227
                }
1228

1229
                try (RepositoryResult<Statement> r = conn.getStatements(npId, null, null, NPA.GRAPH)) {
1230
                    while (r.hasNext()) {
1231
                        Statement st = r.next();
1232
                        IRI p = st.getPredicate();
1233
                        if (p.equals(NPA.HAS_LOAD_NUMBER)
1234
                            || p.equals(NPA.HAS_LOAD_CHECKSUM)
1235
                            || p.equals(NPA.HAS_LOAD_TIMESTAMP)) {
1236
                            continue;
1237
                        }
1238
                        result.add(st);
1239
                    }
1240
                }
1241

1242
                Set<IRI> invalidators = new HashSet<>();
1243
                try (RepositoryResult<Statement> r = conn.getStatements(null, NPX.INVALIDATES, npId, NPA.GRAPH)) {
1244
                    while (r.hasNext()) {
1245
                        Statement st = r.next();
1246
                        result.add(st);
1247
                        if (st.getSubject() instanceof IRI invIri) {
1248
                            invalidators.add(invIri);
1249
                        }
1250
                    }
1251
                }
1252
                for (IRI invIri : invalidators) {
1253
                    try (RepositoryResult<Statement> r = conn.getStatements(invIri, NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY, null, NPA.GRAPH)) {
1254
                        while (r.hasNext()) result.add(r.next());
1255
                    }
1256
                    try (RepositoryResult<Statement> r = conn.getStatements(invIri, NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY_HASH, null, NPA.GRAPH)) {
1257
                        while (r.hasNext()) result.add(r.next());
1258
                    }
1259
                }
1260

1261
                try (RepositoryResult<Statement> r = conn.getStatements(npId, null, null, NPA.NETWORK_GRAPH)) {
1262
                    while (r.hasNext()) result.add(r.next());
1263
                }
1264

1265
                conn.commit();
1266
                success = true;
1267
            } catch (Exception ex) {
1268
                logger.warn("Failed to fetch content of nanopub <{}> from repo '{}': {}", npId, repoName, ex.getMessage(), ex);
1269
                if (conn.isActive()) {
1270
                    conn.rollback();
1271
                }
1272
            }
1273
            if (!success) {
1274
                retries++;
1275
                if (retries >= MAX_RETRIES) {
1276
                    throw new RuntimeException("Failed to fetch nanopub content from " + repoName + " for " + npId + " after " + MAX_RETRIES + " retries");
1277
                }
1278
                long delay = computeBackoffMillis(retries);
1279
                logger.info("Retrying content-fetch of <{}> from repo '{}' in {} ms (attempt {}/{})...", npId, repoName, delay, retries, MAX_RETRIES);
1280
                try {
1281
                    Thread.sleep(delay);
1282
                } catch (InterruptedException x) {
1283
                    Thread.currentThread().interrupt();
1284
                }
1285
            }
1286
        }
1287
        return result;
1288
    }
1289

1290
    @GeneratedFlagForDependentElements
1291
    private static RepositoryConnection loadStatements(String repoName, Statement... statements) {
1292
        RepositoryConnection conn = TripleStore.get().getRepoConnection(repoName);
1293
        // Basic isolation: we only append new statements
1294
        conn.begin(IsolationLevels.READ_COMMITTED);
1295
        for (Statement st : statements) {
1296
            conn.add(st);
1297
        }
1298
        return conn;
1299
    }
1300

1301
    @GeneratedFlagForDependentElements
1302
    static List<Statement> getInvalidatingStatements(IRI npId) {
1303
        List<Statement> invalidatingStatements = new ArrayList<>();
1304
        boolean success = false;
1305
        int retries = 0;
1306
        while (!success) {
1307
            RepositoryConnection conn = TripleStore.get().getRepoConnection("meta");
1308
            try (conn) {
1309
                // Basic isolation because here we only read append-only data.
1310
                conn.begin(IsolationLevels.READ_COMMITTED);
1311

1312
                TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT * { graph <" + NPA.GRAPH + "> { " + "?np <" + NPX.INVALIDATES + "> <" + npId + "> ; <" + NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY + "> ?pubkey . " + "} }").evaluate();
1313
                try (r) {
1314
                    while (r.hasNext()) {
1315
                        BindingSet b = r.next();
1316
                        invalidatingStatements.add(vf.createStatement((IRI) b.getBinding("np").getValue(), NPX.INVALIDATES, npId, NPA.GRAPH));
1317
                        invalidatingStatements.add(vf.createStatement((IRI) b.getBinding("np").getValue(), NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY, b.getBinding("pubkey").getValue(), NPA.GRAPH));
1318
                    }
1319
                }
1320
                conn.commit();
1321
                success = true;
1322
            } catch (Exception ex) {
1323
                logger.warn("Failed to query existing invalidators of <{}> from meta repo: {}", npId, ex.getMessage(), ex);
1324
                if (conn.isActive()) {
1325
                    conn.rollback();
1326
                }
1327
            }
1328
            if (!success) {
1329
                retries++;
1330
                if (retries >= MAX_RETRIES) {
1331
                    throw new RuntimeException("Failed to get invalidating statements for " + npId + " after " + MAX_RETRIES + " retries");
1332
                }
1333
                long delay = computeBackoffMillis(retries);
1334
                logger.info("Retrying invalidator-query for <{}> in {} ms (attempt {}/{})...", npId, delay, retries, MAX_RETRIES);
1335
                try {
1336
                    Thread.sleep(delay);
1337
                } catch (InterruptedException x) {
1338
                    Thread.currentThread().interrupt();
1339
                }
1340
            }
1341
        }
1342
        return invalidatingStatements;
1343
    }
1344

1345
    @GeneratedFlagForDependentElements
1346
    private static void loadNoteToRepo(Resource subj, String note) {
1347
        boolean success = false;
1348
        int retries = 0;
1349
        while (!success) {
1350
            RepositoryConnection conn = TripleStore.get().getAdminRepoConnection();
1351
            try (conn) {
1352
                List<Statement> statements = new ArrayList<>();
1353
                statements.add(vf.createStatement(subj, NPA.NOTE, vf.createLiteral(note), NPA.GRAPH));
1354
                conn.add(statements);
1355
                success = true;
1356
            } catch (Exception ex) {
1357
                logger.warn("Failed to write note \"{}\" to admin repo for <{}>: {}", note, subj, ex.getMessage(), ex);
1358
            }
1359
            if (!success) {
1360
                retries++;
1361
                if (retries >= MAX_RETRIES) {
1362
                    throw new RuntimeException("Failed to load note to repo for " + subj + " after " + MAX_RETRIES + " retries");
1363
                }
1364
                long delay = computeBackoffMillis(retries);
1365
                logger.info("Retrying note-write for <{}> in {} ms (attempt {}/{})...", subj, delay, retries, MAX_RETRIES);
1366
                try {
1367
                    Thread.sleep(delay);
1368
                } catch (InterruptedException x) {
1369
                    Thread.currentThread().interrupt();
1370
                }
1371
            }
1372
        }
1373
    }
1374

1375
    static boolean hasValidSignature(NanopubSignatureElement el) {
1376
        if (el == null) {
6 ✔
1377
            logger.warn("Signature validation skipped: signature element is null (nanopub has no signature)");
9 ✔
1378
            return false;
6 ✔
1379
        }
1380
        try {
1381
            if (SignatureUtils.hasValidSignature(el) && el.getPublicKeyString() != null) {
18 !
1382
                return true;
6 ✔
1383
            }
1384
            logger.warn("Signature invalid for <{}> (pubkey: {})",
12 ✔
1385
                    el.getUri(), el.getPublicKeyString() != null ? el.getPublicKeyString() : "none");
21 !
1386
        } catch (GeneralSecurityException ex) {
3 ✔
1387
            logger.warn("Signature verification threw a security exception for <{}>: {}", el.getUri(), ex.getMessage(), ex);
57 ✔
1388
        }
3 ✔
1389
        return false;
6 ✔
1390
    }
1391

1392
    private static IRI getBaseTrustyUri(Value v) {
1393
        if (!(v instanceof IRI)) {
9 !
1394
            return null;
×
1395
        }
1396
        String s = v.stringValue();
9 ✔
1397
        if (!s.matches(".*[^A-Za-z0-9\\-_]RA[A-Za-z0-9\\-_]{43}([^A-Za-z0-9\\\\-_].{0,43})?")) {
12 ✔
1398
            return null;
6 ✔
1399
        }
1400
        return vf.createIRI(s.replaceFirst("^(.*[^A-Za-z0-9\\-_]RA[A-Za-z0-9\\-_]{43})([^A-Za-z0-9\\\\-_].{0,43})?$", "$1"));
21 ✔
1401
    }
1402

1403
    // TODO: Move this to nanopub library:
1404
    private static boolean isIntroNanopub(Nanopub np) {
1405
        for (Statement st : np.getAssertion()) {
33 ✔
1406
            if (st.getPredicate().equals(NPX.DECLARED_BY)) {
15 ✔
1407
                return true;
6 ✔
1408
            }
1409
        }
3 ✔
1410
        return false;
6 ✔
1411
    }
1412

1413
    /**
1414
     * Check if a nanopub is already loaded in the admin graph.
1415
     *
1416
     * @param npId the nanopub ID
1417
     * @return true if the nanopub is loaded, false otherwise
1418
     */
1419
    @GeneratedFlagForDependentElements
1420
    static boolean isNanopubLoaded(String npId) {
1421
        boolean loaded = false;
1422
        RepositoryConnection conn = TripleStore.get().getRepoConnection("meta");
1423
        try (conn) {
1424
            if (Utils.getObjectForPattern(conn, NPA.GRAPH, vf.createIRI(npId), NPA.HAS_LOAD_NUMBER) != null) {
1425
                loaded = true;
1426
            }
1427
        } catch (Exception ex) {
1428
            logger.warn("Could not check load status of <{}>: {}", npId, ex.getMessage(), ex);
1429
        }
1430
        return loaded;
1431
    }
1432

1433
    private static final ValueFactory vf = SimpleValueFactory.getInstance();
6 ✔
1434

1435
    // TODO remove the constants and use the ones from the nanopub library instead
1436

1437
    /**
1438
     * Template for the query that fetches the status of a repository.
1439
     */
1440
    // Template for .fetchRepoStatus
1441
    private static final String REPO_STATUS_QUERY_TEMPLATE = """
84 ✔
1442
            SELECT * { graph <%s> {
1443
              OPTIONAL { <%s> <%s> ?loadNumber . }
1444
              <%s> <%s> ?count ;
1445
                   <%s> ?checksum .
1446
            } }
1447
            """.formatted(NPA.GRAPH, "%s", NPA.HAS_LOAD_NUMBER, NPA.THIS_REPO, NPA.HAS_NANOPUB_COUNT, NPA.HAS_NANOPUB_CHECKSUM);
6 ✔
1448
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc