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

knowledgepixels / nanopub-query / 31587675387

12 Aug 2026 10:29AM UTC coverage: 76.024% (+0.05%) from 75.976%
31587675387

push

github

web-flow
Merge pull request #183 from knowledgepixels/fix/drop-serializable-rdf4j6

Drop SERIALIZABLE isolation + upgrade RDF4J server to 6.0.0

818 of 1222 branches covered (66.94%)

Branch coverage included in aggregate %.

2413 of 3028 relevant lines covered (79.69%)

12.46 hits per line

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

70.88
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.setting.IntroNanopub;
28
import org.nanopub.vocabulary.NP;
29
import org.nanopub.vocabulary.NPA;
30
import org.nanopub.vocabulary.NPX;
31
import org.nanopub.vocabulary.PAV;
32
import org.slf4j.Logger;
33
import org.slf4j.LoggerFactory;
34

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

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

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

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

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

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

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

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

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

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

167

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

176
        // TODO Ensure proper synchronization and DB rollbacks
177

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

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

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

205
        pubkeyStatement = vf.createStatement(np.getUri(), NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY, vf.createLiteral(el.getPublicKeyString()), NPA.GRAPH);
39 ✔
206
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasValidSignatureForPublicKey, FULL_PUBKEY, npa:graph, meta, full pubkey if signature is valid
207
        metaStatements.add(pubkeyStatement);
18 ✔
208
        pubkeyStatementX = vf.createStatement(np.getUri(), NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY_HASH, vf.createLiteral(Utils.createHash(el.getPublicKeyString())), NPA.GRAPH);
42 ✔
209
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasValidSignatureForPublicKeyHash, PUBKEY_HASH, npa:graph, meta, hex-encoded SHA256 hash if signature is valid
210
        metaStatements.add(pubkeyStatementX);
18 ✔
211

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

217
        Set<IRI> subIris = new HashSet<>();
12 ✔
218
        Set<IRI> otherNps = new HashSet<>();
12 ✔
219
        Set<IRI> invalidated = new HashSet<>();
12 ✔
220
        Set<IRI> retracted = new HashSet<>();
12 ✔
221
        Set<IRI> superseded = new HashSet<>();
12 ✔
222
        String combinedLiterals = "";
6 ✔
223
        for (Statement st : NanopubUtils.getStatements(np)) {
33 ✔
224
            nanopubStatements.add(st);
15 ✔
225

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

310
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_HEAD_GRAPH, np.getHeadUri(), NPA.GRAPH));
36 ✔
311
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasHeadGraph, HEAD_GRAPH, npa:graph, meta, direct link to the head graph of the NANOPUB
312
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_GRAPH, np.getHeadUri(), NPA.GRAPH));
36 ✔
313
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasGraph, GRAPH, npa:graph, meta, generic link to all four graphs of the given NANOPUB
314
        metaStatements.add(vf.createStatement(np.getUri(), NP.HAS_ASSERTION, np.getAssertionUri(), NPA.GRAPH));
36 ✔
315
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, np:hasAssertion, ASSERTION_GRAPH, npa:graph, meta, direct link to the assertion graph of the NANOPUB
316
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_GRAPH, np.getAssertionUri(), NPA.GRAPH));
36 ✔
317
        metaStatements.add(vf.createStatement(np.getUri(), NP.HAS_PROVENANCE, np.getProvenanceUri(), NPA.GRAPH));
36 ✔
318
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, np:hasProvenance, PROVENANCE_GRAPH, npa:graph, meta, direct link to the provenance graph of the NANOPUB
319
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_GRAPH, np.getProvenanceUri(), NPA.GRAPH));
36 ✔
320
        metaStatements.add(vf.createStatement(np.getUri(), NP.HAS_PUBINFO, np.getPubinfoUri(), NPA.GRAPH));
36 ✔
321
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, np:hasPublicationInfo, PUBINFO_GRAPH, npa:graph, meta, direct link to the pubinfo graph of the NANOPUB
322
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_GRAPH, np.getPubinfoUri(), NPA.GRAPH));
36 ✔
323

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

328
        if (isIntroNanopub(np)) {
9 ✔
329
            IntroNanopub introNp = new IntroNanopub(np);
15 ✔
330
            metaStatements.add(vf.createStatement(np.getUri(), NPA.IS_INTRODUCTION_OF, introNp.getUser(), NPA.GRAPH));
36 ✔
331
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:isIntroductionOf, AGENT, npa:graph, meta, linking intro nanopub to the agent it is introducing
332
            for (KeyDeclaration kc : introNp.getKeyDeclarations()) {
33 ✔
333
                metaStatements.add(vf.createStatement(np.getUri(), NPA.DECLARES_PUBKEY, vf.createLiteral(kc.getPublicKeyString()), NPA.GRAPH));
42 ✔
334
                // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:declaresPubkey, FULL_PUBKEY, npa:graph, meta, full pubkey declared by the given intro NANOPUB
335
            }
3 ✔
336
        }
337

338
        try {
339
            timestamp = SimpleTimestampPattern.getCreationTime(np);
12 ✔
340
        } catch (IllegalArgumentException ex) {
×
341
            notes.add("Illegal date/time");
×
342
        }
3 ✔
343
        if (timestamp != null) {
9 !
344
            metaStatements.add(vf.createStatement(np.getUri(), DCTERMS.CREATED, vf.createLiteral(timestamp.getTime()), NPA.GRAPH));
45 ✔
345
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, dct:created, CREATION_DATE, npa:graph, meta, normalized creation timestamp
346
        }
347

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

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

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

381
        metaStatements.addAll(invalidateStatements);
18 ✔
382

383
        allStatements = new ArrayList<>(nanopubStatements);
21 ✔
384
        allStatements.addAll(metaStatements);
18 ✔
385
        allStatements.addAll(invalidatingStatements);
18 ✔
386

387
        textStatements = new ArrayList<>(literalStatements);
21 ✔
388
        textStatements.addAll(metaStatements);
18 ✔
389
        textStatements.addAll(invalidatingStatements);
18 ✔
390

391
        if (FeatureFlags.spacesEnabled()) {
6 !
392
            IRI signedBy = (el.getSigners().size() == 1) ? el.getSigners().iterator().next() : null;
42 !
393
            String pubkeyHash = Utils.createHash(el.getPublicKeyString());
15 ✔
394
            Date createdAt = (timestamp != null) ? timestamp.getTime() : null;
24 !
395
            SpacesExtractor.Context ctx = new SpacesExtractor.Context(ac, signedBy, pubkeyHash, createdAt);
24 ✔
396
            spaceExtractionStatements = SpacesExtractor.extract(np, ctx);
15 ✔
397
        }
398
    }
3 ✔
399

400
    /**
401
     * Get the HTTP client used for fetching nanopublications.
402
     *
403
     * @return the HTTP client
404
     */
405
    static HttpClient getHttpClient() {
406
        if (httpClient == null) {
6 ✔
407
            httpClient = HttpClientBuilder.create().setDefaultRequestConfig(Utils.getHttpRequestConfig()).build();
15 ✔
408
        }
409
        return httpClient;
6 ✔
410
    }
411

412
    /**
413
     * Load the given nanopublication into the database.
414
     *
415
     * @param nanopubUri Nanopublication identifier (URI)
416
     */
417
    public static void load(String nanopubUri) {
418
        if (isNanopubLoaded(nanopubUri)) {
9 !
419
            logger.info("Skipping already-loaded nanopub: <{}>", nanopubUri);
×
420
        } else {
421
            Nanopub np = GetNanopub.get(nanopubUri, getHttpClient());
12 ✔
422
            load(np, -1);
9 ✔
423
        }
424
    }
3 ✔
425

426
    /**
427
     * Load a nanopub into the database.
428
     *
429
     * @param np      the nanopub to load
430
     * @param counter the load counter, only used for logging (or -1 if not known)
431
     * @throws RDF4JException if the loading fails
432
     */
433
    public static void load(Nanopub np, long counter) throws RDF4JException {
434
        NanopubLoader loader = new NanopubLoader(np, counter);
18 ✔
435
        loader.executeLoading();
6 ✔
436
    }
3 ✔
437

438
    @GeneratedFlagForDependentElements
439
    private void executeLoading() {
440
        var runningTasks = new ArrayList<Future<?>>();
441
        Consumer<Runnable> runTask = t -> runningTasks.add(loadingPool.submit(t));
×
442

443
        for (String note : notes) {
444
            loadNoteToRepo(np.getUri(), note);
445
        }
446

447
        if (!aborted) {
448
            // Submit all tasks except the "meta" task
449
            if (timestamp != null) {
450
                if (new Date().getTime() - timestamp.getTimeInMillis() < THIRTY_DAYS) {
451
                    if (FeatureFlags.last30dRepoEnabled()) {
452
                        runTask.accept(() -> loadNanopubToLatest(np.getUri(), allStatements));
×
453
                    }
454
                }
455
            }
456

457
            if (FeatureFlags.textRepoEnabled()) {
458
                runTask.accept(() -> loadNanopubToRepo(np.getUri(), textStatements, "text"));
×
459
            }
460
            if (FeatureFlags.fullRepoEnabled()) {
461
                runTask.accept(() -> loadNanopubToRepo(np.getUri(), allStatements, "full"));
×
462
            }
463
            // Note: "meta" task is deferred until all other tasks complete successfully
464

465
            runTask.accept(() -> loadNanopubToRepo(np.getUri(), allStatements, "pubkey_" + Utils.createHash(el.getPublicKeyString())));
×
466
            //                loadNanopubToRepo(np.getUri(), textStatements, "text-pubkey_" + Utils.createHash(el.getPublicKeyString()));
467
            for (IRI typeIri : NanopubUtils.getTypes(np)) {
468
                // Exclude locally minted IRIs:
469
                if (typeIri.stringValue().startsWith(np.getUri().stringValue())) {
470
                    continue;
471
                }
472
                if (!typeIri.stringValue().matches("https?://.*")) {
473
                    continue;
474
                }
475
                runTask.accept(() -> loadNanopubToRepo(np.getUri(), allStatements, "type_" + Utils.createHash(typeIri)));
×
476
                //                        loadNanopubToRepo(np.getUri(), textStatements, "text-type_" + Utils.createHash(typeIri));
477
            }
478
            //                for (IRI creatorIri : SimpleCreatorPattern.getCreators(np)) {
479
            //                        // Exclude locally minted IRIs:
480
            //                        if (creatorIri.stringValue().startsWith(np.getUri().stringValue())) continue;
481
            //                        if (!creatorIri.stringValue().matches("https?://.*")) continue;
482
            //                        loadNanopubToRepo(np.getUri(), allStatements, "user_" + Utils.createHash(creatorIri));
483
            //                        loadNanopubToRepo(np.getUri(), textStatements, "text-user_" + Utils.createHash(creatorIri));
484
            //                }
485
            //                for (IRI authorIri : SimpleCreatorPattern.getAuthors(np)) {
486
            //                        // Exclude locally minted IRIs:
487
            //                        if (authorIri.stringValue().startsWith(np.getUri().stringValue())) continue;
488
            //                        if (!authorIri.stringValue().matches("https?://.*")) continue;
489
            //                        loadNanopubToRepo(np.getUri(), allStatements, "user_" + Utils.createHash(authorIri));
490
            //                        loadNanopubToRepo(np.getUri(), textStatements, "text-user_" + Utils.createHash(authorIri));
491
            //                }
492

493
            // Write to the spaces repo only when the nanopub carries its own space-relevant
494
            // extractions. Invalidators of space-relevant nanopubs are propagated to spaces
495
            // symmetrically below (forward path in loadInvalidateStatements, reverse path in
496
            // the invalidatorPubkeys block) — mirrors the per-type-repo propagation added in
497
            // PR #103 (commit 09eeb32). The materialiser's invalidation joins
498
            // (?invNp npx:invalidates ?np + ?invNp npa:hasLoadNumber ?ln in the spaces repo's
499
            // npa:graph) stay populated because the invalidators that matter are exactly the
500
            // ones we propagate.
501
            boolean thisNpIsSpaceRelevant = FeatureFlags.spacesEnabled() && !spaceExtractionStatements.isEmpty();
502
            if (thisNpIsSpaceRelevant) {
503
                runTask.accept(() -> loadToSpacesRepo(np.getUri(), allStatements, spaceExtractionStatements));
×
504
            }
505

506
            for (Statement st : invalidateStatements) {
507
                runTask.accept(() -> loadInvalidateStatements(np, el.getPublicKeyString(), st, pubkeyStatement, pubkeyStatementX, allStatements));
×
508
            }
509

510
            // Reverse-order symmetry: when retractors were loaded before this nanopub,
511
            // getInvalidatingStatements (in the constructor) captured their
512
            // `npx:invalidates` markers into invalidatingStatements. Mirror what
513
            // loadInvalidateStatements does in the forward case — load each retractor's
514
            // full content into this nanopub's per-type repos (those types the
515
            // retractor doesn't itself carry), sourced from the retractor's per-pubkey
516
            // repo (the one shard guaranteed to be populated for every successfully
517
            // loaded nanopub). When this nanopub is space-relevant, additionally load
518
            // each retractor into the spaces repo so the materialiser's invalidation
519
            // join sees them regardless of load order.
520
            Map<IRI, String> invalidatorPubkeys = collectInvalidatorPubkeys(invalidatingStatements);
521
            if (!invalidatorPubkeys.isEmpty()) {
522
                Set<IRI> thisNpTypes = NanopubUtils.getTypes(np);
523
                for (Map.Entry<IRI, String> e : invalidatorPubkeys.entrySet()) {
524
                    IRI invIri = e.getKey();
525
                    String invPubkey = e.getValue();
526
                    runTask.accept(() -> loadInvalidatorIntoTypeRepos(invIri, invPubkey, np.getUri(), thisNpTypes));
×
527
                    if (thisNpIsSpaceRelevant) {
528
                        runTask.accept(() -> loadInvalidatorIntoSpacesRepo(invIri, invPubkey, np.getUri()));
×
529
                    }
530
                }
531
            }
532

533
            // Wait for all non-meta tasks to complete successfully before submitting the meta task.
534
            // On failure, cancel the remaining futures so orphaned tasks don't keep running in the
535
            // shared loadingPool and race with the next batch retry (which re-submits the same
536
            // nanopub against the same repos).
537
            for (var task : runningTasks) {
538
                try {
539
                    task.get();
540
                } catch (ExecutionException | InterruptedException ex) {
541
                    for (var t : runningTasks) {
542
                        if (!t.isDone()) {
543
                            t.cancel(true);
544
                        }
545
                    }
546
                    throw new RuntimeException("Error in nanopub loading thread", ex.getCause());
547
                }
548
            }
549

550
            // Now submit and wait for the "meta" task after all other tasks have completed successfully
551
            Future<?> metaTask = loadingPool.submit(() -> loadNanopubToRepo(np.getUri(), metaStatements, "meta"));
×
552
            try {
553
                metaTask.get();
554
            } catch (ExecutionException | InterruptedException ex) {
555
                throw new RuntimeException("Error in nanopub loading thread (meta task)", ex.getCause());
556
            }
557
        }
558
    }
559

560
    private static Long lastUpdateOfLatestRepo = null;
6 ✔
561
    private static long THIRTY_DAYS = 1000L * 60 * 60 * 24 * 30;
6 ✔
562
    private static long ONE_HOUR = 1000L * 60 * 60;
6 ✔
563

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

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

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

773
    /**
774
     * Returns the cumulative count of nanopubs ever loaded into the {@code meta}
775
     * repo, or {@code null} if the value cannot be determined (e.g. the store
776
     * hasn't been initialised yet). Reads the persisted {@code npa:hasNanopubCount}
777
     * triple on first call and caches it in {@link #loadedNanopubCount};
778
     * subsequent fresh loads update the cache in-place.
779
     *
780
     * <p><b>Blocks</b> on a cold cache — use {@link #getCachedLoadedNanopubCount()}
781
     * from the event loop.
782
     */
783
    public static Long getLoadedNanopubCount() {
784
        Long v = loadedNanopubCount;
6 ✔
785
        if (v != null) {
6 ✔
786
            return v;
6 ✔
787
        }
788
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection("meta")) {
12 ✔
789
            Value val = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO, NPA.HAS_NANOPUB_COUNT);
×
790
            if (val != null) {
×
791
                v = Long.parseLong(val.stringValue());
×
792
                loadedNanopubCount = v;
×
793
                return v;
×
794
            }
795
        } catch (NumberFormatException ex) {
×
796
            logger.warn("Malformed npa:hasNanopubCount literal in meta repo (value not parseable as long): {}", ex.getMessage(), ex);
×
797
        } catch (Exception ex) {
3 ✔
798
            logger.warn("Could not read npa:hasNanopubCount from meta repo", ex);
12 ✔
799
        }
×
800
        return null;
6 ✔
801
    }
802

803
    /**
804
     * The cached loaded-nanopub count, without the store read that
805
     * {@link #getLoadedNanopubCount()} falls back to, or {@code null} if nothing has
806
     * populated it yet.
807
     *
808
     * <p>For callers that must not block — specifically
809
     * {@link MainVerticle#applyGlobalHeaders}, which runs on the Vert.x event loop
810
     * for every inbound request. The lazy fallback does blocking HTTP, and on a cold
811
     * cache (i.e. after every restart) that stalled the event loop until the store
812
     * answered; Vert.x's BlockedThreadChecker fired repeatedly on 2026-07-31. Worse,
813
     * with the store unreachable it would have blocked every request for the full
814
     * 10 s connect timeout, turning an RDF4J outage into a total outage of the HTTP
815
     * layer — including the status headers used to diagnose it.
816
     *
817
     * <p>Kept warm off the event loop by {@link #primeHeaderCaches()}.
818
     *
819
     * @return the cached count, or null if not yet known
820
     */
821
    public static Long getCachedLoadedNanopubCount() {
822
        return loadedNanopubCount;
6 ✔
823
    }
824

825
    /**
826
     * The cached loaded-nanopub checksum, without the store read that
827
     * {@link #getLoadedNanopubChecksum()} falls back to, or {@code null} if nothing
828
     * has populated it yet. Same event-loop rationale as
829
     * {@link #getCachedLoadedNanopubCount()}.
830
     *
831
     * @return the cached checksum, or null if not yet known
832
     */
833
    public static String getCachedLoadedNanopubChecksum() {
834
        return loadedNanopubChecksum;
6 ✔
835
    }
836

837
    /**
838
     * Populates the caches read by {@link #getCachedLoadedNanopubCount()} and
839
     * {@link #getCachedLoadedNanopubChecksum()}, going to the store if they are cold.
840
     *
841
     * <p>Both values are otherwise only refreshed when a nanopub is actually loaded,
842
     * so an instance that starts up already caught up would never populate them and
843
     * would serve those headers empty forever. Something off the event loop has to
844
     * prime them; {@link MetricsCollector#updateMetrics()} does, on its own executor.
845
     *
846
     * <p><b>Blocks.</b> Never call from the Vert.x event loop.
847
     */
848
    public static void primeHeaderCaches() {
849
        getLoadedNanopubCount();
6 ✔
850
        getLoadedNanopubChecksum();
6 ✔
851
    }
3 ✔
852

853
    /**
854
     * Returns the order-independent XOR checksum (Base64-encoded) of trusty URIs
855
     * of all nanopubs ever loaded into the {@code meta} repo, or {@code null} if
856
     * the value cannot be determined (e.g. the store hasn't been initialised
857
     * yet). Reads the persisted {@code npa:hasNanopubChecksum} triple on first
858
     * call and caches it in {@link #loadedNanopubChecksum}; subsequent fresh
859
     * loads update the cache in-place alongside {@link #loadedNanopubCount}.
860
     *
861
     * <p><b>Blocks</b> on a cold cache — use {@link #getCachedLoadedNanopubChecksum()}
862
     * from the event loop.
863
     */
864
    public static String getLoadedNanopubChecksum() {
865
        String v = loadedNanopubChecksum;
6 ✔
866
        if (v != null) {
6 !
867
            return v;
×
868
        }
869
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection("meta")) {
12 ✔
870
            Value val = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO, NPA.HAS_NANOPUB_CHECKSUM);
×
871
            if (val != null) {
×
872
                v = val.stringValue();
×
873
                loadedNanopubChecksum = v;
×
874
                return v;
×
875
            }
876
        } catch (Exception ex) {
3 !
877
            logger.warn("Could not read npa:hasNanopubChecksum from meta repo", ex);
12 ✔
878
        }
×
879
        return null;
6 ✔
880
    }
881

882
    private static long fetchSpacesLoadCounter(RepositoryConnection conn) {
883
        Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
884
                com.knowledgepixels.query.vocabulary.SpacesVocab.CURRENT_LOAD_COUNTER);
885
        if (v == null) {
×
886
            return 0;
×
887
        }
888
        try {
889
            return Long.parseLong(v.stringValue());
×
890
        } catch (NumberFormatException ex) {
×
891
            logger.warn("Malformed npa:currentLoadCounter literal in spaces repo (value not parseable as long): \"{}\"", v.stringValue());
×
892
            return 0;
×
893
        }
894
    }
895

896
    record RepoStatus(boolean isLoaded, long count, String checksum) {
36 ✔
897
    }
898

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

930
    @GeneratedFlagForDependentElements
931
    private static void loadInvalidateStatements(Nanopub thisNp, String thisPubkey, Statement invalidateStatement, Statement pubkeyStatement, Statement pubkeyStatementX, List<Statement> thisAllStatements) {
932
        boolean success = false;
933
        int retries = 0;
934
        List<IRI> typesToLoadFullInto = new ArrayList<>();
935
        boolean targetIsSpaceRelevant = false;
936
        while (!success) {
937
            typesToLoadFullInto.clear();
938
            targetIsSpaceRelevant = false;
939
            List<RepositoryConnection> connections = new ArrayList<>();
940
            RepositoryConnection metaConn = TripleStore.get().getRepoConnection("meta");
941
            try {
942
                IRI invalidatedNpId = (IRI) invalidateStatement.getObject();
943
                // Basic isolation because here we only read append-only data.
944
                metaConn.begin(IsolationLevels.READ_COMMITTED);
945

946
                Value pubkeyValue = Utils.getObjectForPattern(metaConn, NPA.GRAPH, invalidatedNpId, NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY);
947
                if (pubkeyValue != null) {
948
                    String pubkey = pubkeyValue.stringValue();
949

950
                    if (!pubkey.equals(thisPubkey)) {
951
                        //logger.info("Adding invalidation expressed in " + thisNp.getUri() + " also to repo for pubkey " + pubkey);
952
                        connections.add(loadStatements("pubkey_" + Utils.createHash(pubkey), invalidateStatement, pubkeyStatement, pubkeyStatementX));
953
//                                                connections.add(loadStatements("text-pubkey_" + Utils.createHash(pubkey), invalidateStatement, pubkeyStatement));
954
                    }
955

956
                    Set<IRI> thisNpTypes = NanopubUtils.getTypes(thisNp);
957
                    for (Value v : Utils.getObjectsForPattern(metaConn, NPA.GRAPH, invalidatedNpId, NPX.HAS_NANOPUB_TYPE)) {
958
                        if (v instanceof IRI typeIri) {
959
                            if (!thisNpTypes.contains(typeIri)) {
960
                                // Defer until after the meta-read commits — full load goes
961
                                // through loadNanopubToRepo, which has its own transaction
962
                                // and retry loop (see post-loop block below).
963
                                typesToLoadFullInto.add(typeIri);
964
                            }
965
                            if (SpacesExtractor.TRIGGER_TYPES.contains(typeIri)) {
966
                                // Target carries a space-relevant type — propagate the
967
                                // retractor into the spaces repo too (deferred, same
968
                                // reason as above).
969
                                targetIsSpaceRelevant = true;
970
                            }
971
                        }
972
                    }
973

974
//                                        for (Value v : Utils.getObjectsForPattern(metaConn, NPA.GRAPH, invalidatedNpId, DCTERMS.CREATOR)) {
975
//                                                IRI creatorIri = (IRI) v;
976
//                                                if (!SimpleCreatorPattern.getCreators(thisNp).contains(creatorIri)) {
977
//                                                        //logger.info("Adding invalidation expressed in " + thisNp.getUri() + " also to repo for user " + creatorIri);
978
//                                                        connections.add(loadStatements("user_" + Utils.createHash(creatorIri), invalidateStatement, pubkeyStatement));
979
//                                                        connections.add(loadStatements("text-user_" + Utils.createHash(creatorIri), invalidateStatement, pubkeyStatement));
980
//                                                }
981
//                                        }
982
                }
983

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

1037
    /**
1038
     * Extracts a map from invalidator IRI to that invalidator's pubkey literal
1039
     * out of an {@code invalidatingStatements} list as produced by
1040
     * {@link #getInvalidatingStatements}. The list interleaves
1041
     * {@code (?inv, npx:invalidates, ?np)} and
1042
     * {@code (?inv, npa:hasValidSignatureForPublicKey, ?pubkey)} triples per
1043
     * invalidator; this helper picks out only the pubkey-binding triples.
1044
     */
1045
    private static Map<IRI, String> collectInvalidatorPubkeys(List<Statement> invalidatingStatements) {
1046
        Map<IRI, String> result = new LinkedHashMap<>();
×
1047
        for (Statement st : invalidatingStatements) {
×
1048
            if (st.getPredicate().equals(NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY)
×
1049
                && st.getSubject() instanceof IRI invIri) {
×
1050
                result.put(invIri, st.getObject().stringValue());
×
1051
            }
1052
        }
×
1053
        return result;
×
1054
    }
1055

1056
    /**
1057
     * Reverse-order counterpart of the forward-order full-content propagation in
1058
     * {@link #loadInvalidateStatements}: when this nanopub had already-loaded
1059
     * retractors at the time of its own load (captured by
1060
     * {@link #getInvalidatingStatements}), load each retractor's full content
1061
     * into this nanopub's per-type repos — restricted to those types the
1062
     * retractor doesn't itself carry (the retractor's own load already populated
1063
     * the type repos it covers).
1064
     *
1065
     * <p>Source is the retractor's per-pubkey repo, which is the one shard
1066
     * unconditionally populated for every successfully-loaded nanopub. The
1067
     * retractor's types are read from the meta repo so we can skip type repos
1068
     * the retractor's own regular load already populated.
1069
     */
1070
    @GeneratedFlagForDependentElements
1071
    private static void loadInvalidatorIntoTypeRepos(IRI invIri, String invPubkey, IRI thisNpId, Set<IRI> thisNpTypes) {
1072
        Set<IRI> invTypes = readInvalidatorTypesFromMeta(invIri, thisNpId);
1073

1074
        List<IRI> typesToLoadInto = new ArrayList<>();
1075
        for (IRI typeIri : thisNpTypes) {
1076
            // Match the regular per-type load loop's exclusion of locally-minted IRIs.
1077
            if (typeIri.stringValue().startsWith(thisNpId.stringValue())) {
1078
                continue;
1079
            }
1080
            if (!typeIri.stringValue().matches("https?://.*")) {
1081
                continue;
1082
            }
1083
            if (!invTypes.contains(typeIri)) {
1084
                typesToLoadInto.add(typeIri);
1085
            }
1086
        }
1087
        if (typesToLoadInto.isEmpty()) {
1088
            return;
1089
        }
1090

1091
        List<Statement> invContent = fetchNanopubAllStatementsFromPubkeyRepo(invIri, invPubkey);
1092
        for (IRI typeIri : typesToLoadInto) {
1093
            loadNanopubToRepo(invIri, invContent, "type_" + Utils.createHash(typeIri));
1094
        }
1095
    }
1096

1097
    /**
1098
     * Reverse-order counterpart for the spaces repo: when a space-relevant nanopub
1099
     * is loaded and {@link #getInvalidatingStatements} captured already-loaded
1100
     * retractors of it, load each retractor's full content into the spaces repo so
1101
     * the materialiser's invalidation join (?invNp npx:invalidates ?np +
1102
     * ?invNp npa:hasLoadNumber ?ln in npa:graph) finds it regardless of the
1103
     * load order between target and retractor.
1104
     *
1105
     * <p>Source is the retractor's per-pubkey repo (the one shard unconditionally
1106
     * populated for every successfully-loaded nanopub). Passes an empty
1107
     * {@code spaceExtraction} list to {@link #loadToSpacesRepo}: by construction
1108
     * the retractor would already be in the spaces repo by its regular spaces-load
1109
     * task if it carried space-relevant extractions of its own.
1110
     * {@link #loadToSpacesRepo} is idempotent on {@code npa:hasLoadNumber}, so
1111
     * the double-load case is a no-op.
1112
     */
1113
    @GeneratedFlagForDependentElements
1114
    private static void loadInvalidatorIntoSpacesRepo(IRI invIri, String invPubkey, IRI thisNpId) {
1115
        List<Statement> invContent = fetchNanopubAllStatementsFromPubkeyRepo(invIri, invPubkey);
1116
        loadToSpacesRepo(invIri, invContent, Collections.emptyList());
1117
    }
1118

1119
    @GeneratedFlagForDependentElements
1120
    private static Set<IRI> readInvalidatorTypesFromMeta(IRI invIri, IRI thisNpId) {
1121
        Set<IRI> invTypes = new HashSet<>();
1122
        boolean success = false;
1123
        int retries = 0;
1124
        while (!success) {
1125
            invTypes.clear();
1126
            RepositoryConnection metaConn = TripleStore.get().getRepoConnection("meta");
1127
            try (metaConn) {
1128
                metaConn.begin(IsolationLevels.READ_COMMITTED);
1129
                for (Value v : Utils.getObjectsForPattern(metaConn, NPA.GRAPH, invIri, NPX.HAS_NANOPUB_TYPE)) {
1130
                    if (v instanceof IRI ti) {
1131
                        invTypes.add(ti);
1132
                    }
1133
                }
1134
                metaConn.commit();
1135
                success = true;
1136
            } catch (Exception ex) {
1137
                logger.warn("Failed to read types for invalidator <{}> (needed for target <{}>): {}", invIri, thisNpId, ex.getMessage(), ex);
1138
                if (metaConn.isActive()) {
1139
                    metaConn.rollback();
1140
                }
1141
            }
1142
            if (!success) {
1143
                retries++;
1144
                if (retries >= MAX_RETRIES) {
1145
                    throw new RuntimeException("Failed to read invalidator types for " + invIri + " after " + MAX_RETRIES + " retries");
1146
                }
1147
                long delay = computeBackoffMillis(retries);
1148
                logger.info("Retrying type-read for invalidator <{}> in {} ms (attempt {}/{})...", invIri, delay, retries, MAX_RETRIES);
1149
                try {
1150
                    Thread.sleep(delay);
1151
                } catch (InterruptedException x) {
1152
                    Thread.currentThread().interrupt();
1153
                }
1154
            }
1155
        }
1156
        return invTypes;
1157
    }
1158

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

1196
                List<IRI> npGraphs = new ArrayList<>();
1197
                try (RepositoryResult<Statement> r = conn.getStatements(npId, NPA.HAS_GRAPH, null, NPA.GRAPH)) {
1198
                    while (r.hasNext()) {
1199
                        Value o = r.next().getObject();
1200
                        if (o instanceof IRI iri) {
1201
                            npGraphs.add(iri);
1202
                        }
1203
                    }
1204
                }
1205

1206
                for (IRI g : npGraphs) {
1207
                    try (RepositoryResult<Statement> r = conn.getStatements(null, null, null, g)) {
1208
                        while (r.hasNext()) result.add(r.next());
1209
                    }
1210
                }
1211

1212
                try (RepositoryResult<Statement> r = conn.getStatements(npId, null, null, NPA.GRAPH)) {
1213
                    while (r.hasNext()) {
1214
                        Statement st = r.next();
1215
                        IRI p = st.getPredicate();
1216
                        if (p.equals(NPA.HAS_LOAD_NUMBER)
1217
                            || p.equals(NPA.HAS_LOAD_CHECKSUM)
1218
                            || p.equals(NPA.HAS_LOAD_TIMESTAMP)) {
1219
                            continue;
1220
                        }
1221
                        result.add(st);
1222
                    }
1223
                }
1224

1225
                Set<IRI> invalidators = new HashSet<>();
1226
                try (RepositoryResult<Statement> r = conn.getStatements(null, NPX.INVALIDATES, npId, NPA.GRAPH)) {
1227
                    while (r.hasNext()) {
1228
                        Statement st = r.next();
1229
                        result.add(st);
1230
                        if (st.getSubject() instanceof IRI invIri) {
1231
                            invalidators.add(invIri);
1232
                        }
1233
                    }
1234
                }
1235
                for (IRI invIri : invalidators) {
1236
                    try (RepositoryResult<Statement> r = conn.getStatements(invIri, NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY, null, NPA.GRAPH)) {
1237
                        while (r.hasNext()) result.add(r.next());
1238
                    }
1239
                    try (RepositoryResult<Statement> r = conn.getStatements(invIri, NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY_HASH, null, NPA.GRAPH)) {
1240
                        while (r.hasNext()) result.add(r.next());
1241
                    }
1242
                }
1243

1244
                try (RepositoryResult<Statement> r = conn.getStatements(npId, null, null, NPA.NETWORK_GRAPH)) {
1245
                    while (r.hasNext()) result.add(r.next());
1246
                }
1247

1248
                conn.commit();
1249
                success = true;
1250
            } catch (Exception ex) {
1251
                logger.warn("Failed to fetch content of nanopub <{}> from repo '{}': {}", npId, repoName, ex.getMessage(), ex);
1252
                if (conn.isActive()) {
1253
                    conn.rollback();
1254
                }
1255
            }
1256
            if (!success) {
1257
                retries++;
1258
                if (retries >= MAX_RETRIES) {
1259
                    throw new RuntimeException("Failed to fetch nanopub content from " + repoName + " for " + npId + " after " + MAX_RETRIES + " retries");
1260
                }
1261
                long delay = computeBackoffMillis(retries);
1262
                logger.info("Retrying content-fetch of <{}> from repo '{}' in {} ms (attempt {}/{})...", npId, repoName, delay, retries, MAX_RETRIES);
1263
                try {
1264
                    Thread.sleep(delay);
1265
                } catch (InterruptedException x) {
1266
                    Thread.currentThread().interrupt();
1267
                }
1268
            }
1269
        }
1270
        return result;
1271
    }
1272

1273
    @GeneratedFlagForDependentElements
1274
    private static RepositoryConnection loadStatements(String repoName, Statement... statements) {
1275
        RepositoryConnection conn = TripleStore.get().getRepoConnection(repoName);
1276
        // Basic isolation: we only append new statements
1277
        conn.begin(IsolationLevels.READ_COMMITTED);
1278
        for (Statement st : statements) {
1279
            conn.add(st);
1280
        }
1281
        return conn;
1282
    }
1283

1284
    @GeneratedFlagForDependentElements
1285
    static List<Statement> getInvalidatingStatements(IRI npId) {
1286
        List<Statement> invalidatingStatements = new ArrayList<>();
1287
        boolean success = false;
1288
        int retries = 0;
1289
        while (!success) {
1290
            RepositoryConnection conn = TripleStore.get().getRepoConnection("meta");
1291
            try (conn) {
1292
                // Basic isolation because here we only read append-only data.
1293
                conn.begin(IsolationLevels.READ_COMMITTED);
1294

1295
                TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT * { graph <" + NPA.GRAPH + "> { " + "?np <" + NPX.INVALIDATES + "> <" + npId + "> ; <" + NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY + "> ?pubkey . " + "} }").evaluate();
1296
                try (r) {
1297
                    while (r.hasNext()) {
1298
                        BindingSet b = r.next();
1299
                        invalidatingStatements.add(vf.createStatement((IRI) b.getBinding("np").getValue(), NPX.INVALIDATES, npId, NPA.GRAPH));
1300
                        invalidatingStatements.add(vf.createStatement((IRI) b.getBinding("np").getValue(), NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY, b.getBinding("pubkey").getValue(), NPA.GRAPH));
1301
                    }
1302
                }
1303
                conn.commit();
1304
                success = true;
1305
            } catch (Exception ex) {
1306
                logger.warn("Failed to query existing invalidators of <{}> from meta repo: {}", npId, ex.getMessage(), ex);
1307
                if (conn.isActive()) {
1308
                    conn.rollback();
1309
                }
1310
            }
1311
            if (!success) {
1312
                retries++;
1313
                if (retries >= MAX_RETRIES) {
1314
                    throw new RuntimeException("Failed to get invalidating statements for " + npId + " after " + MAX_RETRIES + " retries");
1315
                }
1316
                long delay = computeBackoffMillis(retries);
1317
                logger.info("Retrying invalidator-query for <{}> in {} ms (attempt {}/{})...", npId, delay, retries, MAX_RETRIES);
1318
                try {
1319
                    Thread.sleep(delay);
1320
                } catch (InterruptedException x) {
1321
                    Thread.currentThread().interrupt();
1322
                }
1323
            }
1324
        }
1325
        return invalidatingStatements;
1326
    }
1327

1328
    @GeneratedFlagForDependentElements
1329
    private static void loadNoteToRepo(Resource subj, String note) {
1330
        boolean success = false;
1331
        int retries = 0;
1332
        while (!success) {
1333
            RepositoryConnection conn = TripleStore.get().getAdminRepoConnection();
1334
            try (conn) {
1335
                List<Statement> statements = new ArrayList<>();
1336
                statements.add(vf.createStatement(subj, NPA.NOTE, vf.createLiteral(note), NPA.GRAPH));
1337
                conn.add(statements);
1338
                success = true;
1339
            } catch (Exception ex) {
1340
                logger.warn("Failed to write note \"{}\" to admin repo for <{}>: {}", note, subj, ex.getMessage(), ex);
1341
            }
1342
            if (!success) {
1343
                retries++;
1344
                if (retries >= MAX_RETRIES) {
1345
                    throw new RuntimeException("Failed to load note to repo for " + subj + " after " + MAX_RETRIES + " retries");
1346
                }
1347
                long delay = computeBackoffMillis(retries);
1348
                logger.info("Retrying note-write for <{}> in {} ms (attempt {}/{})...", subj, delay, retries, MAX_RETRIES);
1349
                try {
1350
                    Thread.sleep(delay);
1351
                } catch (InterruptedException x) {
1352
                    Thread.currentThread().interrupt();
1353
                }
1354
            }
1355
        }
1356
    }
1357

1358
    static boolean hasValidSignature(NanopubSignatureElement el) {
1359
        if (el == null) {
6 !
1360
            logger.warn("Signature validation skipped: signature element is null (nanopub has no signature)");
×
1361
            return false;
×
1362
        }
1363
        try {
1364
            if (SignatureUtils.hasValidSignature(el) && el.getPublicKeyString() != null) {
18 !
1365
                return true;
6 ✔
1366
            }
1367
            logger.warn("Signature invalid for <{}> (pubkey: {})",
12 ✔
1368
                    el.getUri(), el.getPublicKeyString() != null ? el.getPublicKeyString() : "none");
21 !
1369
        } catch (GeneralSecurityException ex) {
3 ✔
1370
            logger.warn("Signature verification threw a security exception for <{}>: {}", el.getUri(), ex.getMessage(), ex);
57 ✔
1371
        }
3 ✔
1372
        return false;
6 ✔
1373
    }
1374

1375
    private static IRI getBaseTrustyUri(Value v) {
1376
        if (!(v instanceof IRI)) {
9 !
1377
            return null;
×
1378
        }
1379
        String s = v.stringValue();
9 ✔
1380
        if (!s.matches(".*[^A-Za-z0-9\\-_]RA[A-Za-z0-9\\-_]{43}([^A-Za-z0-9\\\\-_].{0,43})?")) {
12 ✔
1381
            return null;
6 ✔
1382
        }
1383
        return vf.createIRI(s.replaceFirst("^(.*[^A-Za-z0-9\\-_]RA[A-Za-z0-9\\-_]{43})([^A-Za-z0-9\\\\-_].{0,43})?$", "$1"));
21 ✔
1384
    }
1385

1386
    // TODO: Move this to nanopub library:
1387
    private static boolean isIntroNanopub(Nanopub np) {
1388
        for (Statement st : np.getAssertion()) {
33 ✔
1389
            if (st.getPredicate().equals(NPX.DECLARED_BY)) {
15 ✔
1390
                return true;
6 ✔
1391
            }
1392
        }
3 ✔
1393
        return false;
6 ✔
1394
    }
1395

1396
    /**
1397
     * Check if a nanopub is already loaded in the admin graph.
1398
     *
1399
     * @param npId the nanopub ID
1400
     * @return true if the nanopub is loaded, false otherwise
1401
     */
1402
    @GeneratedFlagForDependentElements
1403
    static boolean isNanopubLoaded(String npId) {
1404
        boolean loaded = false;
1405
        RepositoryConnection conn = TripleStore.get().getRepoConnection("meta");
1406
        try (conn) {
1407
            if (Utils.getObjectForPattern(conn, NPA.GRAPH, vf.createIRI(npId), NPA.HAS_LOAD_NUMBER) != null) {
1408
                loaded = true;
1409
            }
1410
        } catch (Exception ex) {
1411
            logger.warn("Could not check load status of <{}>: {}", npId, ex.getMessage(), ex);
1412
        }
1413
        return loaded;
1414
    }
1415

1416
    private static final ValueFactory vf = SimpleValueFactory.getInstance();
6 ✔
1417

1418
    // TODO remove the constants and use the ones from the nanopub library instead
1419

1420
    /**
1421
     * Template for the query that fetches the status of a repository.
1422
     */
1423
    // Template for .fetchRepoStatus
1424
    private static final String REPO_STATUS_QUERY_TEMPLATE = """
84 ✔
1425
            SELECT * { graph <%s> {
1426
              OPTIONAL { <%s> <%s> ?loadNumber . }
1427
              <%s> <%s> ?count ;
1428
                   <%s> ?checksum .
1429
            } }
1430
            """.formatted(NPA.GRAPH, "%s", NPA.HAS_LOAD_NUMBER, NPA.THIS_REPO, NPA.HAS_NANOPUB_COUNT, NPA.HAS_NANOPUB_CHECKSUM);
6 ✔
1431
}
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