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

knowledgepixels / nanopub-query / 26029185718

18 May 2026 10:55AM UTC coverage: 58.476% (-0.4%) from 58.908%
26029185718

push

github

web-flow
Merge pull request #100 from knowledgepixels/feature/loaded-nanopub-count-header

feat: expose Nanopub-Query-Loaded-Nanopub-Count response header

496 of 926 branches covered (53.56%)

Branch coverage included in aggregate %.

1315 of 2171 relevant lines covered (60.57%)

9.36 hits per line

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

69.17
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.nanopub.Nanopub;
18
import org.nanopub.NanopubUtils;
19
import org.nanopub.SimpleCreatorPattern;
20
import org.nanopub.SimpleTimestampPattern;
21
import org.nanopub.extra.security.KeyDeclaration;
22
import org.nanopub.extra.security.MalformedCryptoElementException;
23
import org.nanopub.extra.security.NanopubSignatureElement;
24
import org.nanopub.extra.security.SignatureUtils;
25
import org.nanopub.extra.server.GetNanopub;
26
import org.nanopub.extra.setting.IntroNanopub;
27
import org.nanopub.vocabulary.NP;
28
import org.nanopub.vocabulary.NPA;
29
import org.nanopub.vocabulary.NPX;
30
import org.nanopub.vocabulary.PAV;
31
import org.slf4j.Logger;
32
import org.slf4j.LoggerFactory;
33

34

35
import java.security.GeneralSecurityException;
36
import java.util.*;
37
import java.util.concurrent.ExecutionException;
38
import java.util.concurrent.Executors;
39
import java.util.concurrent.Future;
40
import java.util.concurrent.ThreadLocalRandom;
41
import java.util.concurrent.ThreadPoolExecutor;
42
import java.util.function.Consumer;
43

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

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

52
    /**
53
     * Cached count of nanopubs ever loaded into the {@code full} repo. Maintained
54
     * for {@link MainVerticle}'s {@code Nanopub-Query-Loaded-Nanopub-Count}
55
     * response header. Mirrors the persisted {@code npa:hasNanopubCount} triple
56
     * that {@link #loadNanopubToRepo} maintains; invalidations don't decrement
57
     * (they're recorded as separate {@code npx:invalidates} markers), so this
58
     * is a cumulative count including superseded/retracted nanopubs — matching
59
     * the registry-side {@code Nanopub-Registry-Nanopub-Count} semantics.
60
     * Populated lazily on first read; bumped post-commit on each fresh load.
61
     */
62
    static volatile Long loadedNanopubCount = null;
6✔
63

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

81
    /**
82
     * Returns the sleep delay in ms for the given 1-indexed retry attempt. Delay
83
     * is {@link #BACKOFF_BASE_MS}{@code [attempt-1]} perturbed by ±50 % uniform
84
     * jitter, clamped to be non-negative.
85
     *
86
     * @param attempt 1-indexed retry attempt number
87
     * @return the computed sleep delay in ms
88
     */
89
    static long computeBackoffMillis(int attempt) {
90
        long base = BACKOFF_BASE_MS[Math.min(attempt - 1, BACKOFF_BASE_MS.length - 1)];
×
91
        long jitter = ThreadLocalRandom.current().nextLong(base + 1) - base / 2;
×
92
        return Math.max(0L, base + jitter);
×
93
    }
94
    private Nanopub np;
95
    private NanopubSignatureElement el = null;
9✔
96
    private List<Statement> metaStatements = new ArrayList<>();
15✔
97
    private List<Statement> nanopubStatements = new ArrayList<>();
15✔
98
    private List<Statement> literalStatements = new ArrayList<>();
15✔
99
    private List<Statement> invalidateStatements = new ArrayList<>();
15✔
100
    private List<Statement> textStatements, allStatements;
101
    private List<Statement> spaceExtractionStatements = new ArrayList<>();
15✔
102
    private Calendar timestamp = null;
9✔
103
    private Statement pubkeyStatement, pubkeyStatementX;
104
    private List<String> notes = new ArrayList<>();
15✔
105
    private boolean aborted = false;
9✔
106
    private static final Logger log = LoggerFactory.getLogger(NanopubLoader.class);
9✔
107

108

109
    NanopubLoader(Nanopub np, long counter) {
6✔
110
        this.np = np;
9✔
111
        if (counter >= 0) {
12✔
112
            log.info("Loading {}: {}", counter, np.getUri());
24✔
113
        } else {
114
            log.info("Loading: {}", np.getUri());
15✔
115
        }
116

117
        // TODO Ensure proper synchronization and DB rollbacks
118

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

121
        String ac = TrustyUriUtils.getArtifactCode(np.getUri().toString());
15✔
122
        if (!np.getHeadUri().toString().contains(ac) || !np.getAssertionUri().toString().contains(ac) || !np.getProvenanceUri().toString().contains(ac) || !np.getPubinfoUri().toString().contains(ac)) {
72!
123
            notes.add("could not load nanopub as not all graphs contained the artifact code");
×
124
            aborted = true;
×
125
            return;
×
126
        }
127

128
        try {
129
            el = SignatureUtils.getSignatureElement(np);
12✔
130
        } catch (MalformedCryptoElementException ex) {
×
131
            notes.add("Signature error");
×
132
        }
3✔
133
        if (!hasValidSignature(el)) {
12✔
134
            aborted = true;
9✔
135
            return;
3✔
136
        }
137

138
        pubkeyStatement = vf.createStatement(np.getUri(), NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY, vf.createLiteral(el.getPublicKeyString()), NPA.GRAPH);
39✔
139
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasValidSignatureForPublicKey, FULL_PUBKEY, npa:graph, meta, full pubkey if signature is valid
140
        metaStatements.add(pubkeyStatement);
18✔
141
        pubkeyStatementX = vf.createStatement(np.getUri(), NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY_HASH, vf.createLiteral(Utils.createHash(el.getPublicKeyString())), NPA.GRAPH);
42✔
142
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasValidSignatureForPublicKeyHash, PUBKEY_HASH, npa:graph, meta, hex-encoded SHA256 hash if signature is valid
143
        metaStatements.add(pubkeyStatementX);
18✔
144

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

150
        Set<IRI> subIris = new HashSet<>();
12✔
151
        Set<IRI> otherNps = new HashSet<>();
12✔
152
        Set<IRI> invalidated = new HashSet<>();
12✔
153
        Set<IRI> retracted = new HashSet<>();
12✔
154
        Set<IRI> superseded = new HashSet<>();
12✔
155
        String combinedLiterals = "";
6✔
156
        for (Statement st : NanopubUtils.getStatements(np)) {
33✔
157
            nanopubStatements.add(st);
15✔
158

159
            if (st.getPredicate().toString().contains(ac)) {
18!
160
                subIris.add(st.getPredicate());
×
161
            } else {
162
                IRI b = getBaseTrustyUri(st.getPredicate());
12✔
163
                if (b != null) otherNps.add(b);
6!
164
            }
165
            if (st.getPredicate().equals(NPX.RETRACTS) && st.getObject() instanceof IRI) {
15!
166
                retracted.add((IRI) st.getObject());
×
167
            }
168
            if (st.getPredicate().equals(NPX.INVALIDATES) && st.getObject() instanceof IRI) {
15!
169
                invalidated.add((IRI) st.getObject());
×
170
            }
171
            if (st.getSubject().equals(np.getUri()) && st.getObject() instanceof IRI) {
30✔
172
                if (st.getPredicate().equals(NPX.SUPERSEDES)) {
15✔
173
                    superseded.add((IRI) st.getObject());
18✔
174
                }
175
                if (st.getObject().toString().matches(".*[^A-Za-z0-9\\-_]RA[A-Za-z0-9\\-_]{43}")) {
18✔
176
                    metaStatements.add(vf.createStatement(np.getUri(), st.getPredicate(), st.getObject(), NPA.NETWORK_GRAPH));
39✔
177
                    // @ADMIN-TRIPLE-TABLE@ NANOPUB1, RELATION, NANOPUB2, npa:networkGraph, meta, any inter-nanopub relation found in NANOPUB1
178
                }
179
                if (st.getContext().equals(np.getPubinfoUri())) {
18✔
180
                    if (st.getPredicate().equals(NPX.INTRODUCES) || st.getPredicate().equals(NPX.DESCRIBES) || st.getPredicate().equals(NPX.EMBEDS)) {
45!
181
                        metaStatements.add(vf.createStatement(np.getUri(), st.getPredicate(), st.getObject(), NPA.GRAPH));
39✔
182
                        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:introduces, THING, npa:graph, meta, when such a triple is present in pubinfo of NANOPUB
183
                        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:describes, THING, npa:graph, meta, when such a triple is present in pubinfo of NANOPUB
184
                        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:embeds, THING, npa:graph, meta, when such a triple is present in pubinfo of NANOPUB
185
                    }
186
                }
187
            }
188
            if (st.getSubject().toString().contains(ac)) {
18✔
189
                subIris.add((IRI) st.getSubject());
21✔
190
            } else {
191
                IRI b = getBaseTrustyUri(st.getSubject());
12✔
192
                if (b != null) otherNps.add(b);
6!
193
            }
194
            if (st.getObject() instanceof IRI) {
12✔
195
                if (st.getObject().toString().contains(ac)) {
18✔
196
                    subIris.add((IRI) st.getObject());
21✔
197
                } else {
198
                    IRI b = getBaseTrustyUri(st.getObject());
12✔
199
                    if (b != null) otherNps.add(b);
18✔
200
                }
3✔
201
            } else {
202
                combinedLiterals += st.getObject().stringValue().replaceAll("\\s+", " ") + "\n";
27✔
203
//                                if (st.getSubject().equals(np.getUri()) && !st.getSubject().equals(HAS_FILTER_LITERAL)) {
204
//                                        literalStatements.add(vf.createStatement(np.getUri(), st.getPredicate(), st.getObject(), LITERAL_GRAPH));
205
//                                } else {
206
//                                        literalStatements.add(vf.createStatement(np.getUri(), HAS_LITERAL, st.getObject(), LITERAL_GRAPH));
207
//                                }
208
            }
209
        }
3✔
210
        subIris.remove(np.getUri());
15✔
211
        subIris.remove(np.getAssertionUri());
15✔
212
        subIris.remove(np.getProvenanceUri());
15✔
213
        subIris.remove(np.getPubinfoUri());
15✔
214
        for (IRI i : subIris) {
30✔
215
            metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_SUB_IRI, i, NPA.GRAPH));
33✔
216
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasSubIri, SUB_IRI, npa:graph, meta, for any IRI minted in the namespace of the NANOPUB
217
        }
3✔
218
        for (IRI i : otherNps) {
30✔
219
            metaStatements.add(vf.createStatement(np.getUri(), NPA.REFERS_TO_NANOPUB, i, NPA.NETWORK_GRAPH));
33✔
220
            // @ADMIN-TRIPLE-TABLE@ NANOPUB1, npa:refersToNanopub, NANOPUB2, npa:networkGraph, meta, generic inter-nanopub relation
221
        }
3✔
222
        for (IRI i : invalidated) {
18!
223
            invalidateStatements.add(vf.createStatement(np.getUri(), NPX.INVALIDATES, i, NPA.GRAPH));
×
224
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:invalidates, INVALIDATED_NANOPUB, npa:graph, meta, if the NANOPUB retracts or supersedes another nanopub
225
        }
×
226
        for (IRI i : retracted) {
18!
227
            invalidateStatements.add(vf.createStatement(np.getUri(), NPX.INVALIDATES, i, NPA.GRAPH));
×
228
            metaStatements.add(vf.createStatement(np.getUri(), NPX.RETRACTS, i, NPA.GRAPH));
×
229
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:retracts, RETRACTED_NANOPUB, npa:graph, meta, if the NANOPUB retracts another nanopub
230
        }
×
231
        for (IRI i : superseded) {
30✔
232
            invalidateStatements.add(vf.createStatement(np.getUri(), NPX.INVALIDATES, i, NPA.GRAPH));
33✔
233
            metaStatements.add(vf.createStatement(np.getUri(), NPX.SUPERSEDES, i, NPA.GRAPH));
33✔
234
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:supersedes, SUPERSEDED_NANOPUB, npa:graph, meta, if the NANOPUB supersedes another nanopub
235
        }
3✔
236

237
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_HEAD_GRAPH, np.getHeadUri(), NPA.GRAPH));
36✔
238
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasHeadGraph, HEAD_GRAPH, npa:graph, meta, direct link to the head graph of the NANOPUB
239
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_GRAPH, np.getHeadUri(), NPA.GRAPH));
36✔
240
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasGraph, GRAPH, npa:graph, meta, generic link to all four graphs of the given NANOPUB
241
        metaStatements.add(vf.createStatement(np.getUri(), NP.HAS_ASSERTION, np.getAssertionUri(), NPA.GRAPH));
36✔
242
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, np:hasAssertion, ASSERTION_GRAPH, npa:graph, meta, direct link to the assertion graph of the NANOPUB
243
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_GRAPH, np.getAssertionUri(), NPA.GRAPH));
36✔
244
        metaStatements.add(vf.createStatement(np.getUri(), NP.HAS_PROVENANCE, np.getProvenanceUri(), NPA.GRAPH));
36✔
245
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, np:hasProvenance, PROVENANCE_GRAPH, npa:graph, meta, direct link to the provenance graph of the NANOPUB
246
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_GRAPH, np.getProvenanceUri(), NPA.GRAPH));
36✔
247
        metaStatements.add(vf.createStatement(np.getUri(), NP.HAS_PUBINFO, np.getPubinfoUri(), NPA.GRAPH));
36✔
248
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, np:hasPublicationInfo, PUBINFO_GRAPH, npa:graph, meta, direct link to the pubinfo graph of the NANOPUB
249
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_GRAPH, np.getPubinfoUri(), NPA.GRAPH));
36✔
250

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

255
        if (isIntroNanopub(np)) {
9✔
256
            IntroNanopub introNp = new IntroNanopub(np);
15✔
257
            metaStatements.add(vf.createStatement(np.getUri(), NPA.IS_INTRODUCTION_OF, introNp.getUser(), NPA.GRAPH));
36✔
258
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:isIntroductionOf, AGENT, npa:graph, meta, linking intro nanopub to the agent it is introducing
259
            for (KeyDeclaration kc : introNp.getKeyDeclarations()) {
33✔
260
                metaStatements.add(vf.createStatement(np.getUri(), NPA.DECLARES_PUBKEY, vf.createLiteral(kc.getPublicKeyString()), NPA.GRAPH));
42✔
261
                // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:declaresPubkey, FULL_PUBKEY, npa:graph, meta, full pubkey declared by the given intro NANOPUB
262
            }
3✔
263
        }
264

265
        try {
266
            timestamp = SimpleTimestampPattern.getCreationTime(np);
12✔
267
        } catch (IllegalArgumentException ex) {
×
268
            notes.add("Illegal date/time");
×
269
        }
3✔
270
        if (timestamp != null) {
9!
271
            metaStatements.add(vf.createStatement(np.getUri(), DCTERMS.CREATED, vf.createLiteral(timestamp.getTime()), NPA.GRAPH));
45✔
272
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, dct:created, CREATION_DATE, npa:graph, meta, normalized creation timestamp
273
        }
274

275
        String literalFilter = "_pubkey_" + Utils.createHash(el.getPublicKeyString());
18✔
276
        for (IRI typeIri : NanopubUtils.getTypes(np)) {
33✔
277
            metaStatements.add(vf.createStatement(np.getUri(), NPX.HAS_NANOPUB_TYPE, typeIri, NPA.GRAPH));
33✔
278
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:hasNanopubType, NANOPUB_TYPE, npa:graph, meta, type of NANOPUB
279
            literalFilter += " _type_" + Utils.createHash(typeIri);
15✔
280
        }
3✔
281
        String label = NanopubUtils.getLabel(np);
9✔
282
        if (label != null) {
6!
283
            metaStatements.add(vf.createStatement(np.getUri(), RDFS.LABEL, vf.createLiteral(label), NPA.GRAPH));
39✔
284
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, rdfs:label, LABEL, npa:graph, meta, label of NANOPUB
285
        }
286
        String description = NanopubUtils.getDescription(np);
9✔
287
        if (description != null) {
6✔
288
            metaStatements.add(vf.createStatement(np.getUri(), DCTERMS.DESCRIPTION, vf.createLiteral(description), NPA.GRAPH));
39✔
289
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, dct:description, LABEL, npa:graph, meta, description of NANOPUB
290
        }
291
        for (IRI creatorIri : SimpleCreatorPattern.getCreators(np)) {
33✔
292
            metaStatements.add(vf.createStatement(np.getUri(), DCTERMS.CREATOR, creatorIri, NPA.GRAPH));
33✔
293
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, dct:creator, CREATOR, npa:graph, meta, creator of NANOPUB (can be several)
294
        }
3✔
295
        for (IRI authorIri : SimpleCreatorPattern.getAuthors(np)) {
21!
296
            metaStatements.add(vf.createStatement(np.getUri(), PAV.AUTHORED_BY, authorIri, NPA.GRAPH));
×
297
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, pav:authoredBy, AUTHOR, npa:graph, meta, author of NANOPUB (can be several)
298
        }
×
299

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

305
        // Any statements that express that the currently processed nanopub is already invalidated:
306
        List<Statement> invalidatingStatements = getInvalidatingStatements(np.getUri());
12✔
307

308
        metaStatements.addAll(invalidateStatements);
18✔
309

310
        allStatements = new ArrayList<>(nanopubStatements);
21✔
311
        allStatements.addAll(metaStatements);
18✔
312
        allStatements.addAll(invalidatingStatements);
15✔
313

314
        textStatements = new ArrayList<>(literalStatements);
21✔
315
        textStatements.addAll(metaStatements);
18✔
316
        textStatements.addAll(invalidatingStatements);
15✔
317

318
        if (FeatureFlags.spacesEnabled()) {
6!
319
            IRI signedBy = (el.getSigners().size() == 1) ? el.getSigners().iterator().next() : null;
42!
320
            String pubkeyHash = Utils.createHash(el.getPublicKeyString());
15✔
321
            Date createdAt = (timestamp != null) ? timestamp.getTime() : null;
24!
322
            SpacesExtractor.Context ctx = new SpacesExtractor.Context(ac, signedBy, pubkeyHash, createdAt);
24✔
323
            spaceExtractionStatements = SpacesExtractor.extract(np, ctx);
15✔
324
        }
325
    }
3✔
326

327
    /**
328
     * Get the HTTP client used for fetching nanopublications.
329
     *
330
     * @return the HTTP client
331
     */
332
    static HttpClient getHttpClient() {
333
        if (httpClient == null) {
6✔
334
            httpClient = HttpClientBuilder.create().setDefaultRequestConfig(Utils.getHttpRequestConfig()).build();
15✔
335
        }
336
        return httpClient;
6✔
337
    }
338

339
    /**
340
     * Load the given nanopublication into the database.
341
     *
342
     * @param nanopubUri Nanopublication identifier (URI)
343
     */
344
    public static void load(String nanopubUri) {
345
        if (isNanopubLoaded(nanopubUri)) {
9!
346
            log.info("Already loaded: {}", nanopubUri);
×
347
        } else {
348
            Nanopub np = GetNanopub.get(nanopubUri, getHttpClient());
12✔
349
            load(np, -1);
9✔
350
        }
351
    }
3✔
352

353
    /**
354
     * Load a nanopub into the database.
355
     *
356
     * @param np      the nanopub to load
357
     * @param counter the load counter, only used for logging (or -1 if not known)
358
     * @throws RDF4JException if the loading fails
359
     */
360
    public static void load(Nanopub np, long counter) throws RDF4JException {
361
        NanopubLoader loader = new NanopubLoader(np, counter);
18✔
362
        loader.executeLoading();
6✔
363
    }
3✔
364

365
    @GeneratedFlagForDependentElements
366
    private void executeLoading() {
367
        var runningTasks = new ArrayList<Future<?>>();
368
        Consumer<Runnable> runTask = t -> runningTasks.add(loadingPool.submit(t));
×
369

370
        for (String note : notes) {
371
            loadNoteToRepo(np.getUri(), note);
372
        }
373

374
        if (!aborted) {
375
            // Submit all tasks except the "meta" task
376
            if (timestamp != null) {
377
                if (new Date().getTime() - timestamp.getTimeInMillis() < THIRTY_DAYS) {
378
                    if (FeatureFlags.last30dRepoEnabled()) {
379
                        runTask.accept(() -> loadNanopubToLatest(np.getUri(), allStatements));
×
380
                    }
381
                }
382
            }
383

384
            if (FeatureFlags.textRepoEnabled()) {
385
                runTask.accept(() -> loadNanopubToRepo(np.getUri(), textStatements, "text"));
×
386
            }
387
            if (FeatureFlags.fullRepoEnabled()) {
388
                runTask.accept(() -> loadNanopubToRepo(np.getUri(), allStatements, "full"));
×
389
            }
390
            // Note: "meta" task is deferred until all other tasks complete successfully
391

392
            runTask.accept(() -> loadNanopubToRepo(np.getUri(), allStatements, "pubkey_" + Utils.createHash(el.getPublicKeyString())));
×
393
            //                loadNanopubToRepo(np.getUri(), textStatements, "text-pubkey_" + Utils.createHash(el.getPublicKeyString()));
394
            for (IRI typeIri : NanopubUtils.getTypes(np)) {
395
                // Exclude locally minted IRIs:
396
                if (typeIri.stringValue().startsWith(np.getUri().stringValue())) continue;
397
                if (!typeIri.stringValue().matches("https?://.*")) continue;
398
                runTask.accept(() -> loadNanopubToRepo(np.getUri(), allStatements, "type_" + Utils.createHash(typeIri)));
×
399
                //                        loadNanopubToRepo(np.getUri(), textStatements, "text-type_" + Utils.createHash(typeIri));
400
            }
401
            //                for (IRI creatorIri : SimpleCreatorPattern.getCreators(np)) {
402
            //                        // Exclude locally minted IRIs:
403
            //                        if (creatorIri.stringValue().startsWith(np.getUri().stringValue())) continue;
404
            //                        if (!creatorIri.stringValue().matches("https?://.*")) continue;
405
            //                        loadNanopubToRepo(np.getUri(), allStatements, "user_" + Utils.createHash(creatorIri));
406
            //                        loadNanopubToRepo(np.getUri(), textStatements, "text-user_" + Utils.createHash(creatorIri));
407
            //                }
408
            //                for (IRI authorIri : SimpleCreatorPattern.getAuthors(np)) {
409
            //                        // Exclude locally minted IRIs:
410
            //                        if (authorIri.stringValue().startsWith(np.getUri().stringValue())) continue;
411
            //                        if (!authorIri.stringValue().matches("https?://.*")) continue;
412
            //                        loadNanopubToRepo(np.getUri(), allStatements, "user_" + Utils.createHash(authorIri));
413
            //                        loadNanopubToRepo(np.getUri(), textStatements, "text-user_" + Utils.createHash(authorIri));
414
            //                }
415

416
            if (FeatureFlags.spacesEnabled() && !spaceExtractionStatements.isEmpty()) {
417
                runTask.accept(() -> loadToSpacesRepo(np.getUri(), allStatements, spaceExtractionStatements));
×
418
            }
419

420
            for (Statement st : invalidateStatements) {
421
                runTask.accept(() -> loadInvalidateStatements(np, el.getPublicKeyString(), st, pubkeyStatement, pubkeyStatementX));
×
422
            }
423

424
            // Wait for all non-meta tasks to complete successfully before submitting the meta task
425
            for (var task : runningTasks) {
426
                try {
427
                    task.get();
428
                } catch (ExecutionException | InterruptedException ex) {
429
                    throw new RuntimeException("Error in nanopub loading thread", ex.getCause());
430
                }
431
            }
432

433
            // Now submit and wait for the "meta" task after all other tasks have completed successfully
434
            Future<?> metaTask = loadingPool.submit(() -> loadNanopubToRepo(np.getUri(), metaStatements, "meta"));
×
435
            try {
436
                metaTask.get();
437
            } catch (ExecutionException | InterruptedException ex) {
438
                throw new RuntimeException("Error in nanopub loading thread (meta task)", ex.getCause());
439
            }
440
        }
441
    }
442

443
    private static Long lastUpdateOfLatestRepo = null;
6✔
444
    private static long THIRTY_DAYS = 1000L * 60 * 60 * 24 * 30;
6✔
445
    private static long ONE_HOUR = 1000L * 60 * 60;
6✔
446

447
    @GeneratedFlagForDependentElements
448
    private static void loadNanopubToLatest(IRI npId, List<Statement> statements) {
449
        boolean success = false;
450
        int retries = 0;
451
        while (!success) {
452
            RepositoryConnection conn = TripleStore.get().getRepoConnection("last30d");
453
            try (conn) {
454
                // Read committed, because deleting old nanopubs is idempotent. Inserts do not collide
455
                // with deletes, because we are not inserting old nanopubs.
456
                conn.begin(IsolationLevels.READ_COMMITTED);
457
                conn.add(statements);
458
                if (lastUpdateOfLatestRepo == null || new Date().getTime() - lastUpdateOfLatestRepo > ONE_HOUR) {
459
                    log.trace("Remove old nanopubs...");
460
                    Literal thirtyDaysAgo = vf.createLiteral(new Date(new Date().getTime() - THIRTY_DAYS));
461
                    TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT * { graph <" + NPA.GRAPH + "> { " + "?np <" + DCTERMS.CREATED + "> ?date . " + "filter ( ?date < ?thirtydaysago ) " + "} }");
462
                    q.setBinding("thirtydaysago", thirtyDaysAgo);
463
                    try (TupleQueryResult r = q.evaluate()) {
464
                        while (r.hasNext()) {
465
                            BindingSet b = r.next();
466
                            IRI oldNpId = (IRI) b.getBinding("np").getValue();
467
                            log.trace("Remove old nanopub: {}", oldNpId);
468
                            for (Value v : Utils.getObjectsForPattern(conn, NPA.GRAPH, oldNpId, NPA.HAS_GRAPH)) {
469
                                // Remove all four nanopub graphs:
470
                                conn.remove((Resource) null, (IRI) null, (Value) null, (IRI) v);
471
                            }
472
                            // Remove nanopubs in admin graphs:
473
                            conn.remove(oldNpId, null, null, NPA.GRAPH);
474
                            conn.remove(oldNpId, null, null, NPA.NETWORK_GRAPH);
475
                        }
476
                    }
477
                    lastUpdateOfLatestRepo = new Date().getTime();
478
                }
479
                conn.commit();
480
                success = true;
481
            } catch (Exception ex) {
482
                log.warn("Could not load nanopub {} to last30d repo.", npId, ex);
483
                if (conn.isActive()) conn.rollback();
484
            }
485
            if (!success) {
486
                retries++;
487
                if (retries >= MAX_RETRIES) {
488
                    throw new RuntimeException("Failed to load nanopub " + npId + " to last30d repo after " + MAX_RETRIES + " retries");
489
                }
490
                long delay = computeBackoffMillis(retries);
491
                log.info("Retrying in {} ms for nanopub {} in last30d (attempt {}/{})...", delay, npId, retries, MAX_RETRIES);
492
                try {
493
                    Thread.sleep(delay);
494
                } catch (InterruptedException x) {
495
                    Thread.currentThread().interrupt();
496
                }
497
            }
498
        }
499
    }
500

501
    @GeneratedFlagForDependentElements
502
    private static void loadNanopubToRepo(IRI npId, List<Statement> statements, String repoName) {
503
        boolean success = false;
504
        int retries = 0;
505
        while (!success) {
506
            RepositoryConnection conn = TripleStore.get().getRepoConnection(repoName);
507
            long newCountForCache = -1;
508
            try (conn) {
509
                // Serializable, because write skew would cause the chain of hashes to be broken.
510
                // The inserts must be done serially.
511
                conn.begin(IsolationLevels.SERIALIZABLE);
512
                var repoStatus = fetchRepoStatus(conn, npId);
513
                if (repoStatus.isLoaded) {
514
                    log.info("Already loaded: {}", npId);
515
                } else {
516
                    String newChecksum = NanopubUtils.updateXorChecksum(npId, repoStatus.checksum);
517
                    conn.remove(NPA.THIS_REPO, NPA.HAS_NANOPUB_COUNT, null, NPA.GRAPH);
518
                    conn.remove(NPA.THIS_REPO, NPA.HAS_NANOPUB_CHECKSUM, null, NPA.GRAPH);
519
                    conn.add(NPA.THIS_REPO, NPA.HAS_NANOPUB_COUNT, vf.createLiteral(repoStatus.count + 1), NPA.GRAPH);
520
                    // @ADMIN-TRIPLE-TABLE@ REPO, npa:hasNanopubCount, NANOPUB_COUNT, npa:graph, admin, number of nanopubs loaded
521
                    conn.add(NPA.THIS_REPO, NPA.HAS_NANOPUB_CHECKSUM, vf.createLiteral(newChecksum), NPA.GRAPH);
522
                    // @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)
523
                    conn.add(npId, NPA.HAS_LOAD_NUMBER, vf.createLiteral(repoStatus.count), NPA.GRAPH);
524
                    // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasLoadNumber, LOAD_NUMBER, npa:graph, admin, the sequential number at which this NANOPUB was loaded
525
                    conn.add(npId, NPA.HAS_LOAD_CHECKSUM, vf.createLiteral(newChecksum), NPA.GRAPH);
526
                    // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasLoadChecksum, LOAD_CHECKSUM, npa:graph, admin, the checksum of all loaded nanopubs after loading the given NANOPUB
527
                    conn.add(npId, NPA.HAS_LOAD_TIMESTAMP, vf.createLiteral(new Date()), NPA.GRAPH);
528
                    // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasLoadTimestamp, LOAD_TIMESTAMP, npa:graph, admin, the time point at which this NANOPUB was loaded
529
                    conn.add(statements);
530
                    if ("full".equals(repoName)) {
531
                        newCountForCache = repoStatus.count + 1;
532
                    }
533
                }
534
                conn.commit();
535
                if (newCountForCache >= 0) {
536
                    loadedNanopubCount = newCountForCache;
537
                }
538
                success = true;
539
            } catch (Exception ex) {
540
                log.warn("Could not load nanopub {} to repo {}.", npId, repoName, ex);
541
                if (conn.isActive()) conn.rollback();
542
            }
543
            if (!success) {
544
                retries++;
545
                if (retries >= MAX_RETRIES) {
546
                    throw new RuntimeException("Failed to load nanopub " + npId + " to repo " + repoName + " after " + MAX_RETRIES + " retries");
547
                }
548
                long delay = computeBackoffMillis(retries);
549
                log.info("Retrying in {} ms for nanopub {} in repo {} (attempt {}/{})...", delay, npId, repoName, retries, MAX_RETRIES);
550
                try {
551
                    Thread.sleep(delay);
552
                } catch (InterruptedException x) {
553
                    Thread.currentThread().interrupt();
554
                }
555
            }
556
        }
557
    }
558

559
    /**
560
     * Writes the raw nanopub statements (all four graphs) into the {@code spaces}
561
     * repo alongside the pre-computed extraction statements (which target
562
     * {@code npa:spacesGraph}). Stamps the load-number on the nanopub IRI and bumps
563
     * {@code npa:thisRepo npa:currentLoadCounter} in {@code npa:graph}, all within
564
     * one serializable transaction.
565
     *
566
     * <p>Idempotent: if the nanopub already has a {@code npa:hasLoadNumber} stamp in
567
     * {@code npa:graph} of the {@code spaces} repo, this is a no-op.
568
     *
569
     * @param npId            nanopub IRI
570
     * @param nanopubTriples  raw nanopub statements (all four graphs + meta)
571
     * @param spaceExtraction summary triples destined for {@code npa:spacesGraph}
572
     */
573
    @GeneratedFlagForDependentElements
574
    private static void loadToSpacesRepo(IRI npId, List<Statement> nanopubTriples,
575
                                         List<Statement> spaceExtraction) {
576
        boolean success = false;
577
        int retries = 0;
578
        while (!success) {
579
            RepositoryConnection conn = TripleStore.get().getRepoConnection("spaces");
580
            try (conn) {
581
                conn.begin(IsolationLevels.SERIALIZABLE);
582
                // Idempotency: skip if this nanopub is already stamped in this repo.
583
                if (Utils.getObjectForPattern(conn, NPA.GRAPH, npId, NPA.HAS_LOAD_NUMBER) != null) {
584
                    conn.commit();
585
                    success = true;
586
                    continue;
587
                }
588
                long newCounter = fetchSpacesLoadCounter(conn) + 1;
589
                conn.remove(NPA.THIS_REPO,
590
                        com.knowledgepixels.query.vocabulary.SpacesVocab.CURRENT_LOAD_COUNTER,
591
                        null, NPA.GRAPH);
592
                conn.add(NPA.THIS_REPO,
593
                        com.knowledgepixels.query.vocabulary.SpacesVocab.CURRENT_LOAD_COUNTER,
594
                        vf.createLiteral(newCounter), NPA.GRAPH);
595
                conn.add(npId, NPA.HAS_LOAD_NUMBER, vf.createLiteral(newCounter), NPA.GRAPH);
596
                conn.add(nanopubTriples);
597
                conn.add(spaceExtraction);
598
                conn.commit();
599
                success = true;
600
            } catch (Exception ex) {
601
                log.warn("Could not load nanopub {} to spaces repo.", npId, ex);
602
                if (conn.isActive()) conn.rollback();
603
            }
604
            if (!success) {
605
                retries++;
606
                if (retries >= MAX_RETRIES) {
607
                    throw new RuntimeException("Failed to load nanopub " + npId + " to spaces repo after " + MAX_RETRIES + " retries");
608
                }
609
                long delay = computeBackoffMillis(retries);
610
                log.info("Retrying in {} ms for nanopub {} in spaces repo (attempt {}/{})...", delay, npId, retries, MAX_RETRIES);
611
                try {
612
                    Thread.sleep(delay);
613
                } catch (InterruptedException x) {
614
                    Thread.currentThread().interrupt();
615
                }
616
            }
617
        }
618
    }
619

620
    /**
621
     * Returns the cumulative count of nanopubs ever loaded into the {@code full}
622
     * repo, or {@code null} if the value cannot be determined (e.g. the store
623
     * hasn't been initialised yet). Reads the persisted {@code npa:hasNanopubCount}
624
     * triple on first call and caches it in {@link #loadedNanopubCount};
625
     * subsequent fresh loads update the cache in-place.
626
     */
627
    public static Long getLoadedNanopubCount() {
628
        Long v = loadedNanopubCount;
6✔
629
        if (v != null) return v;
12✔
630
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection("full")) {
12✔
631
            Value val = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO, NPA.HAS_NANOPUB_COUNT);
×
632
            if (val != null) {
×
633
                v = Long.parseLong(val.stringValue());
×
634
                loadedNanopubCount = v;
×
635
                return v;
×
636
            }
637
        } catch (NumberFormatException ex) {
×
638
            log.warn("Invalid npa:hasNanopubCount literal in full repo", ex);
×
639
        } catch (Exception ex) {
3✔
640
            log.warn("Could not read npa:hasNanopubCount from full repo", ex);
12✔
641
        }
×
642
        return null;
6✔
643
    }
644

645
    private static long fetchSpacesLoadCounter(RepositoryConnection conn) {
646
        Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
647
                com.knowledgepixels.query.vocabulary.SpacesVocab.CURRENT_LOAD_COUNTER);
648
        if (v == null) return 0;
×
649
        try {
650
            return Long.parseLong(v.stringValue());
×
651
        } catch (NumberFormatException ex) {
×
652
            log.warn("Invalid npa:currentLoadCounter literal in spaces repo: {}", v);
×
653
            return 0;
×
654
        }
655
    }
656

657
    private record RepoStatus(boolean isLoaded, long count, String checksum) {
×
658
    }
659

660
    /**
661
     * To execute before loading a nanopub: check if the nanopub is already loaded and what is the
662
     * current load counter and checksum. This effectively batches three queries into one.
663
     * This method must be called from within a transaction.
664
     *
665
     * @param conn repo connection
666
     * @param npId nanopub ID
667
     * @return the current status
668
     */
669
    @GeneratedFlagForDependentElements
670
    private static RepoStatus fetchRepoStatus(RepositoryConnection conn, IRI npId) {
671
        var result = conn.prepareTupleQuery(QueryLanguage.SPARQL, REPO_STATUS_QUERY_TEMPLATE.formatted(npId)).evaluate();
672
        try (result) {
673
            if (!result.hasNext()) {
674
                // This may happen if the repo was created, but is completely empty.
675
                return new RepoStatus(false, 0, NanopubUtils.INIT_CHECKSUM);
676
            }
677
            var row = result.next();
678
            return new RepoStatus(row.hasBinding("loadNumber"), Long.parseLong(row.getBinding("count").getValue().stringValue()), row.getBinding("checksum").getValue().stringValue());
679
        }
680
    }
681

682
    @GeneratedFlagForDependentElements
683
    private static void loadInvalidateStatements(Nanopub thisNp, String thisPubkey, Statement invalidateStatement, Statement pubkeyStatement, Statement pubkeyStatementX) {
684
        boolean success = false;
685
        int retries = 0;
686
        while (!success) {
687
            List<RepositoryConnection> connections = new ArrayList<>();
688
            RepositoryConnection metaConn = TripleStore.get().getRepoConnection("meta");
689
            try {
690
                IRI invalidatedNpId = (IRI) invalidateStatement.getObject();
691
                // Basic isolation because here we only read append-only data.
692
                metaConn.begin(IsolationLevels.READ_COMMITTED);
693

694
                Value pubkeyValue = Utils.getObjectForPattern(metaConn, NPA.GRAPH, invalidatedNpId, NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY);
695
                if (pubkeyValue != null) {
696
                    String pubkey = pubkeyValue.stringValue();
697

698
                    if (!pubkey.equals(thisPubkey)) {
699
                        //log.info("Adding invalidation expressed in " + thisNp.getUri() + " also to repo for pubkey " + pubkey);
700
                        connections.add(loadStatements("pubkey_" + Utils.createHash(pubkey), invalidateStatement, pubkeyStatement, pubkeyStatementX));
701
//                                                connections.add(loadStatements("text-pubkey_" + Utils.createHash(pubkey), invalidateStatement, pubkeyStatement));
702
                    }
703

704
                    // Collect target types so we can both propagate per-type AND decide
705
                    // whether the target is space-relevant in a single pass over meta.
706
                    Set<IRI> targetTypes = new HashSet<>();
707
                    for (Value v : Utils.getObjectsForPattern(metaConn, NPA.GRAPH, invalidatedNpId, NPX.HAS_NANOPUB_TYPE)) {
708
                        if (v instanceof IRI typeIri) targetTypes.add(typeIri);
709
                    }
710
                    Set<IRI> thisNpTypes = NanopubUtils.getTypes(thisNp);
711
                    for (IRI typeIri : targetTypes) {
712
                        if (!thisNpTypes.contains(typeIri)) {
713
                            //log.info("Adding invalidation expressed in " + thisNp.getUri() + " also to repo for type " + typeIri);
714
                            connections.add(loadStatements("type_" + Utils.createHash(typeIri), invalidateStatement, pubkeyStatement, pubkeyStatementX));
715
//                                                        connections.add(loadStatements("text-type_" + Utils.createHash(typeIri), invalidateStatement, pubkeyStatement));
716
                        }
717
                    }
718

719
                    // Emit an npa:Invalidation entry into the spaces repo if the target
720
                    // had any space-relevant type. Piggybacks on the type lookup above
721
                    // so we don't re-read meta.
722
                    if (FeatureFlags.spacesEnabled() && SpacesExtractor.isSpaceRelevant(targetTypes)) {
723
                        List<Statement> invEntry = buildInvalidationEntry(thisNp, invalidatedNpId, targetTypes, thisPubkey);
724
                        if (!invEntry.isEmpty()) {
725
                            connections.add(loadStatements("spaces", invEntry.toArray(new Statement[0])));
726
                        }
727
                    }
728

729
//                                        for (Value v : Utils.getObjectsForPattern(metaConn, NPA.GRAPH, invalidatedNpId, DCTERMS.CREATOR)) {
730
//                                                IRI creatorIri = (IRI) v;
731
//                                                if (!SimpleCreatorPattern.getCreators(thisNp).contains(creatorIri)) {
732
//                                                        //log.info("Adding invalidation expressed in " + thisNp.getUri() + " also to repo for user " + creatorIri);
733
//                                                        connections.add(loadStatements("user_" + Utils.createHash(creatorIri), invalidateStatement, pubkeyStatement));
734
//                                                        connections.add(loadStatements("text-user_" + Utils.createHash(creatorIri), invalidateStatement, pubkeyStatement));
735
//                                                }
736
//                                        }
737
                }
738

739
                metaConn.commit();
740
                // TODO handle case that some commits succeed and some fail
741
                for (RepositoryConnection c : connections) c.commit();
742
                success = true;
743
            } catch (Exception ex) {
744
                log.warn("Could not load invalidate statements for {}.", thisNp.getUri(), ex);
745
                if (metaConn.isActive()) metaConn.rollback();
746
                for (RepositoryConnection c : connections) {
747
                    if (c.isActive()) c.rollback();
748
                }
749
            } finally {
750
                metaConn.close();
751
                for (RepositoryConnection c : connections) c.close();
752
            }
753
            if (!success) {
754
                retries++;
755
                if (retries >= MAX_RETRIES) {
756
                    throw new RuntimeException("Failed to load invalidate statements for " + thisNp.getUri() + " after " + MAX_RETRIES + " retries");
757
                }
758
                long delay = computeBackoffMillis(retries);
759
                log.info("Retrying in {} ms for invalidate statements of {} (attempt {}/{})...", delay, thisNp.getUri(), retries, MAX_RETRIES);
760
                try {
761
                    Thread.sleep(delay);
762
                } catch (InterruptedException x) {
763
                    Thread.currentThread().interrupt();
764
                }
765
            }
766
        }
767
    }
768

769
    /**
770
     * Builds the statements for an {@code npa:Invalidation} entry describing a
771
     * space-relevant retraction/supersession. Caller writes these into the
772
     * {@code spaces} repo.
773
     *
774
     * @param thisNp        the invalidator nanopub
775
     * @param invalidatedNp IRI of the invalidated target
776
     * @param targetTypes   the target's types (already read from the meta repo)
777
     * @param thisPubkey    the invalidator's signing pubkey
778
     * @return the invalidation-entry statements, or an empty list if no signer is known
779
     */
780
    private static List<Statement> buildInvalidationEntry(Nanopub thisNp, IRI invalidatedNp,
781
                                                          Set<IRI> targetTypes, String thisPubkey) {
782
        String artifactCode = TrustyUriUtils.getArtifactCode(thisNp.getUri().toString());
×
783
        if (artifactCode == null || artifactCode.isEmpty()) return Collections.emptyList();
×
784
        IRI signer = null;
×
785
        for (Statement st : thisNp.getPubinfo()) {
×
786
            if (!st.getSubject().equals(thisNp.getUri())) continue;
×
787
            if (!st.getPredicate().equals(NPX.SIGNED_BY)) continue;
×
788
            if (st.getObject() instanceof IRI signerIri) {
×
789
                signer = signerIri;
×
790
                break;
×
791
            }
792
        }
×
793
        Date createdAt = null;
×
794
        try {
795
            Calendar ts = SimpleTimestampPattern.getCreationTime(thisNp);
×
796
            if (ts != null) createdAt = ts.getTime();
×
797
        } catch (IllegalArgumentException ignored) {
×
798
            // pubinfo timestamp missing or malformed; extraction entry simply omits dct:created.
799
        }
×
800
        SpacesExtractor.Context ctx = new SpacesExtractor.Context(
×
801
                artifactCode, signer, Utils.createHash(thisPubkey), createdAt);
×
802
        return SpacesExtractor.extractInvalidation(thisNp, invalidatedNp, targetTypes, ctx);
×
803
    }
804

805
    @GeneratedFlagForDependentElements
806
    private static RepositoryConnection loadStatements(String repoName, Statement... statements) {
807
        RepositoryConnection conn = TripleStore.get().getRepoConnection(repoName);
808
        // Basic isolation: we only append new statements
809
        conn.begin(IsolationLevels.READ_COMMITTED);
810
        for (Statement st : statements) {
811
            conn.add(st);
812
        }
813
        return conn;
814
    }
815

816
    @GeneratedFlagForDependentElements
817
    static List<Statement> getInvalidatingStatements(IRI npId) {
818
        List<Statement> invalidatingStatements = new ArrayList<>();
819
        boolean success = false;
820
        int retries = 0;
821
        while (!success) {
822
            RepositoryConnection conn = TripleStore.get().getRepoConnection("meta");
823
            try (conn) {
824
                // Basic isolation because here we only read append-only data.
825
                conn.begin(IsolationLevels.READ_COMMITTED);
826

827
                TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT * { graph <" + NPA.GRAPH + "> { " + "?np <" + NPX.INVALIDATES + "> <" + npId + "> ; <" + NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY + "> ?pubkey . " + "} }").evaluate();
828
                try (r) {
829
                    while (r.hasNext()) {
830
                        BindingSet b = r.next();
831
                        invalidatingStatements.add(vf.createStatement((IRI) b.getBinding("np").getValue(), NPX.INVALIDATES, npId, NPA.GRAPH));
832
                        invalidatingStatements.add(vf.createStatement((IRI) b.getBinding("np").getValue(), NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY, b.getBinding("pubkey").getValue(), NPA.GRAPH));
833
                    }
834
                }
835
                conn.commit();
836
                success = true;
837
            } catch (Exception ex) {
838
                log.warn("Could not load invalidating statements for {}.", npId, ex);
839
                if (conn.isActive()) conn.rollback();
840
            }
841
            if (!success) {
842
                retries++;
843
                if (retries >= MAX_RETRIES) {
844
                    throw new RuntimeException("Failed to get invalidating statements for " + npId + " after " + MAX_RETRIES + " retries");
845
                }
846
                long delay = computeBackoffMillis(retries);
847
                log.info("Retrying in {} ms for invalidating statements of {} (attempt {}/{})...", delay, npId, retries, MAX_RETRIES);
848
                try {
849
                    Thread.sleep(delay);
850
                } catch (InterruptedException x) {
851
                    Thread.currentThread().interrupt();
852
                }
853
            }
854
        }
855
        return invalidatingStatements;
856
    }
857

858
    @GeneratedFlagForDependentElements
859
    private static void loadNoteToRepo(Resource subj, String note) {
860
        boolean success = false;
861
        int retries = 0;
862
        while (!success) {
863
            RepositoryConnection conn = TripleStore.get().getAdminRepoConnection();
864
            try (conn) {
865
                List<Statement> statements = new ArrayList<>();
866
                statements.add(vf.createStatement(subj, NPA.NOTE, vf.createLiteral(note), NPA.GRAPH));
867
                conn.add(statements);
868
                success = true;
869
            } catch (Exception ex) {
870
                log.warn("Could not load note to repo for {}.", subj, ex);
871
            }
872
            if (!success) {
873
                retries++;
874
                if (retries >= MAX_RETRIES) {
875
                    throw new RuntimeException("Failed to load note to repo for " + subj + " after " + MAX_RETRIES + " retries");
876
                }
877
                long delay = computeBackoffMillis(retries);
878
                log.info("Retrying in {} ms for note on {} (attempt {}/{})...", delay, subj, retries, MAX_RETRIES);
879
                try {
880
                    Thread.sleep(delay);
881
                } catch (InterruptedException x) {
882
                    Thread.currentThread().interrupt();
883
                }
884
            }
885
        }
886
    }
887

888
    static boolean hasValidSignature(NanopubSignatureElement el) {
889
        try {
890
            if (el != null && SignatureUtils.hasValidSignature(el) && el.getPublicKeyString() != null) {
24!
891
                return true;
6✔
892
            }
893
        } catch (GeneralSecurityException ex) {
3✔
894
            log.warn("Signature validation failed for signature element {}", el.getUri(), ex);
18✔
895
        }
3✔
896
        return false;
6✔
897
    }
898

899
    private static IRI getBaseTrustyUri(Value v) {
900
        if (!(v instanceof IRI)) return null;
9!
901
        String s = v.stringValue();
9✔
902
        if (!s.matches(".*[^A-Za-z0-9\\-_]RA[A-Za-z0-9\\-_]{43}([^A-Za-z0-9\\\\-_].{0,43})?")) {
12✔
903
            return null;
6✔
904
        }
905
        return vf.createIRI(s.replaceFirst("^(.*[^A-Za-z0-9\\-_]RA[A-Za-z0-9\\-_]{43})([^A-Za-z0-9\\\\-_].{0,43})?$", "$1"));
21✔
906
    }
907

908
    // TODO: Move this to nanopub library:
909
    private static boolean isIntroNanopub(Nanopub np) {
910
        for (Statement st : np.getAssertion()) {
33✔
911
            if (st.getPredicate().equals(NPX.DECLARED_BY)) return true;
21✔
912
        }
3✔
913
        return false;
6✔
914
    }
915

916
    /**
917
     * Check if a nanopub is already loaded in the admin graph.
918
     *
919
     * @param npId the nanopub ID
920
     * @return true if the nanopub is loaded, false otherwise
921
     */
922
    @GeneratedFlagForDependentElements
923
    static boolean isNanopubLoaded(String npId) {
924
        boolean loaded = false;
925
        RepositoryConnection conn = TripleStore.get().getRepoConnection("meta");
926
        try (conn) {
927
            if (Utils.getObjectForPattern(conn, NPA.GRAPH, vf.createIRI(npId), NPA.HAS_LOAD_NUMBER) != null) {
928
                loaded = true;
929
            }
930
        } catch (Exception ex) {
931
            log.warn("Could not check whether nanopub is loaded.", ex);
932
        }
933
        return loaded;
934
    }
935

936
    private static ValueFactory vf = SimpleValueFactory.getInstance();
6✔
937

938
    // TODO remove the constants and use the ones from the nanopub library instead
939

940
    /**
941
     * Template for the query that fetches the status of a repository.
942
     */
943
    // Template for .fetchRepoStatus
944
    private static final String REPO_STATUS_QUERY_TEMPLATE = """
84✔
945
            SELECT * { graph <%s> {
946
              OPTIONAL { <%s> <%s> ?loadNumber . }
947
              <%s> <%s> ?count ;
948
                   <%s> ?checksum .
949
            } }
950
            """.formatted(NPA.GRAPH, "%s", NPA.HAS_LOAD_NUMBER, NPA.THIS_REPO, NPA.HAS_NANOPUB_COUNT, NPA.HAS_NANOPUB_CHECKSUM);
6✔
951
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc