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

knowledgepixels / nanopub-query / 24669686981

20 Apr 2026 01:37PM UTC coverage: 60.242% (+0.3%) from 59.905%
24669686981

push

github

web-flow
Merge pull request #76 from knowledgepixels/feat/optional-repo-disables

feat: change 9 — optional per-instance disable of full/text/last30d repo writes

293 of 544 branches covered (53.86%)

Branch coverage included in aggregate %.

851 of 1355 relevant lines covered (62.8%)

8.97 hits per line

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

81.87
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
import com.knowledgepixels.query.vocabulary.GEN;
35

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

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

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

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

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

96

97
    NanopubLoader(Nanopub np, long counter) {
6✔
98
        this.np = np;
9✔
99
        if (counter >= 0) {
12✔
100
            log.info("Loading {}: {}", counter, np.getUri());
24✔
101
        } else {
102
            log.info("Loading: {}", np.getUri());
15✔
103
        }
104

105
        // TODO Ensure proper synchronization and DB rollbacks
106

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

109
        String ac = TrustyUriUtils.getArtifactCode(np.getUri().toString());
15✔
110
        if (!np.getHeadUri().toString().contains(ac) || !np.getAssertionUri().toString().contains(ac) || !np.getProvenanceUri().toString().contains(ac) || !np.getPubinfoUri().toString().contains(ac)) {
72!
111
            notes.add("could not load nanopub as not all graphs contained the artifact code");
×
112
            aborted = true;
×
113
            return;
×
114
        }
115

116
        try {
117
            el = SignatureUtils.getSignatureElement(np);
12✔
118
        } catch (MalformedCryptoElementException ex) {
×
119
            notes.add("Signature error");
×
120
        }
3✔
121
        if (!hasValidSignature(el)) {
12✔
122
            aborted = true;
9✔
123
            return;
3✔
124
        }
125

126
        pubkeyStatement = vf.createStatement(np.getUri(), NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY, vf.createLiteral(el.getPublicKeyString()), NPA.GRAPH);
39✔
127
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasValidSignatureForPublicKey, FULL_PUBKEY, npa:graph, meta, full pubkey if signature is valid
128
        metaStatements.add(pubkeyStatement);
18✔
129
        pubkeyStatementX = vf.createStatement(np.getUri(), NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY_HASH, vf.createLiteral(Utils.createHash(el.getPublicKeyString())), NPA.GRAPH);
42✔
130
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasValidSignatureForPublicKeyHash, PUBKEY_HASH, npa:graph, meta, hex-encoded SHA256 hash if signature is valid
131
        metaStatements.add(pubkeyStatementX);
18✔
132

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

138
        Set<IRI> subIris = new HashSet<>();
12✔
139
        Set<IRI> otherNps = new HashSet<>();
12✔
140
        Set<IRI> invalidated = new HashSet<>();
12✔
141
        Set<IRI> retracted = new HashSet<>();
12✔
142
        Set<IRI> superseded = new HashSet<>();
12✔
143
        String combinedLiterals = "";
6✔
144
        for (Statement st : NanopubUtils.getStatements(np)) {
33✔
145
            nanopubStatements.add(st);
15✔
146

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

225
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_HEAD_GRAPH, np.getHeadUri(), NPA.GRAPH));
36✔
226
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasHeadGraph, HEAD_GRAPH, npa:graph, meta, direct link to the head graph of the NANOPUB
227
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_GRAPH, np.getHeadUri(), NPA.GRAPH));
36✔
228
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasGraph, GRAPH, npa:graph, meta, generic link to all four graphs of the given NANOPUB
229
        metaStatements.add(vf.createStatement(np.getUri(), NP.HAS_ASSERTION, np.getAssertionUri(), NPA.GRAPH));
36✔
230
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, np:hasAssertion, ASSERTION_GRAPH, npa:graph, meta, direct link to the assertion graph of the NANOPUB
231
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_GRAPH, np.getAssertionUri(), NPA.GRAPH));
36✔
232
        metaStatements.add(vf.createStatement(np.getUri(), NP.HAS_PROVENANCE, np.getProvenanceUri(), NPA.GRAPH));
36✔
233
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, np:hasProvenance, PROVENANCE_GRAPH, npa:graph, meta, direct link to the provenance graph of the NANOPUB
234
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_GRAPH, np.getProvenanceUri(), NPA.GRAPH));
36✔
235
        metaStatements.add(vf.createStatement(np.getUri(), NP.HAS_PUBINFO, np.getPubinfoUri(), NPA.GRAPH));
36✔
236
        // @ADMIN-TRIPLE-TABLE@ NANOPUB, np:hasPublicationInfo, PUBINFO_GRAPH, npa:graph, meta, direct link to the pubinfo graph of the NANOPUB
237
        metaStatements.add(vf.createStatement(np.getUri(), NPA.HAS_GRAPH, np.getPubinfoUri(), NPA.GRAPH));
36✔
238

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

243
        if (isIntroNanopub(np)) {
9✔
244
            IntroNanopub introNp = new IntroNanopub(np);
15✔
245
            metaStatements.add(vf.createStatement(np.getUri(), NPA.IS_INTRODUCTION_OF, introNp.getUser(), NPA.GRAPH));
36✔
246
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:isIntroductionOf, AGENT, npa:graph, meta, linking intro nanopub to the agent it is introducing
247
            for (KeyDeclaration kc : introNp.getKeyDeclarations()) {
33✔
248
                metaStatements.add(vf.createStatement(np.getUri(), NPA.DECLARES_PUBKEY, vf.createLiteral(kc.getPublicKeyString()), NPA.GRAPH));
42✔
249
                // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:declaresPubkey, FULL_PUBKEY, npa:graph, meta, full pubkey declared by the given intro NANOPUB
250
            }
3✔
251
        }
252

253
        try {
254
            timestamp = SimpleTimestampPattern.getCreationTime(np);
12✔
255
        } catch (IllegalArgumentException ex) {
×
256
            notes.add("Illegal date/time");
×
257
        }
3✔
258
        if (timestamp != null) {
9!
259
            metaStatements.add(vf.createStatement(np.getUri(), DCTERMS.CREATED, vf.createLiteral(timestamp.getTime()), NPA.GRAPH));
45✔
260
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, dct:created, CREATION_DATE, npa:graph, meta, normalized creation timestamp
261
        }
262

263
        String literalFilter = "_pubkey_" + Utils.createHash(el.getPublicKeyString());
18✔
264
        for (IRI typeIri : NanopubUtils.getTypes(np)) {
33✔
265
            metaStatements.add(vf.createStatement(np.getUri(), NPX.HAS_NANOPUB_TYPE, typeIri, NPA.GRAPH));
33✔
266
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, npx:hasNanopubType, NANOPUB_TYPE, npa:graph, meta, type of NANOPUB
267
            literalFilter += " _type_" + Utils.createHash(typeIri);
15✔
268
        }
3✔
269
        // Side-effecting call: populates SpaceRegistry as gen:Space-typed nanopubs flow through.
270
        // Consumers of the registry (extraction, materialization) land in later steps of #62.
271
        detectAndRegisterSpaces(np);
9✔
272
        String label = NanopubUtils.getLabel(np);
9✔
273
        if (label != null) {
6!
274
            metaStatements.add(vf.createStatement(np.getUri(), RDFS.LABEL, vf.createLiteral(label), NPA.GRAPH));
39✔
275
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, rdfs:label, LABEL, npa:graph, meta, label of NANOPUB
276
        }
277
        String description = NanopubUtils.getDescription(np);
9✔
278
        if (description != null) {
6✔
279
            metaStatements.add(vf.createStatement(np.getUri(), DCTERMS.DESCRIPTION, vf.createLiteral(description), NPA.GRAPH));
39✔
280
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, dct:description, LABEL, npa:graph, meta, description of NANOPUB
281
        }
282
        for (IRI creatorIri : SimpleCreatorPattern.getCreators(np)) {
33✔
283
            metaStatements.add(vf.createStatement(np.getUri(), DCTERMS.CREATOR, creatorIri, NPA.GRAPH));
33✔
284
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, dct:creator, CREATOR, npa:graph, meta, creator of NANOPUB (can be several)
285
        }
3✔
286
        for (IRI authorIri : SimpleCreatorPattern.getAuthors(np)) {
21!
287
            metaStatements.add(vf.createStatement(np.getUri(), PAV.AUTHORED_BY, authorIri, NPA.GRAPH));
×
288
            // @ADMIN-TRIPLE-TABLE@ NANOPUB, pav:authoredBy, AUTHOR, npa:graph, meta, author of NANOPUB (can be several)
289
        }
×
290

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

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

299
        metaStatements.addAll(invalidateStatements);
18✔
300

301
        allStatements = new ArrayList<>(nanopubStatements);
21✔
302
        allStatements.addAll(metaStatements);
18✔
303
        allStatements.addAll(invalidatingStatements);
15✔
304

305
        textStatements = new ArrayList<>(literalStatements);
21✔
306
        textStatements.addAll(metaStatements);
18✔
307
        textStatements.addAll(invalidatingStatements);
15✔
308
    }
3✔
309

310
    /**
311
     * Get the HTTP client used for fetching nanopublications.
312
     *
313
     * @return the HTTP client
314
     */
315
    static HttpClient getHttpClient() {
316
        if (httpClient == null) {
6✔
317
            httpClient = HttpClientBuilder.create().setDefaultRequestConfig(Utils.getHttpRequestConfig()).build();
15✔
318
        }
319
        return httpClient;
6✔
320
    }
321

322
    /**
323
     * Load the given nanopublication into the database.
324
     *
325
     * @param nanopubUri Nanopublication identifier (URI)
326
     */
327
    public static void load(String nanopubUri) {
328
        if (isNanopubLoaded(nanopubUri)) {
9!
329
            log.info("Already loaded: {}", nanopubUri);
×
330
        } else {
331
            Nanopub np = GetNanopub.get(nanopubUri, getHttpClient());
12✔
332
            load(np, -1);
9✔
333
        }
334
    }
3✔
335

336
    /**
337
     * Load a nanopub into the database.
338
     *
339
     * @param np      the nanopub to load
340
     * @param counter the load counter, only used for logging (or -1 if not known)
341
     * @throws RDF4JException if the loading fails
342
     */
343
    public static void load(Nanopub np, long counter) throws RDF4JException {
344
        NanopubLoader loader = new NanopubLoader(np, counter);
18✔
345
        loader.executeLoading();
6✔
346
    }
3✔
347

348
    @GeneratedFlagForDependentElements
349
    private void executeLoading() {
350
        var runningTasks = new ArrayList<Future<?>>();
351
        Consumer<Runnable> runTask = t -> runningTasks.add(loadingPool.submit(t));
×
352

353
        for (String note : notes) {
354
            loadNoteToRepo(np.getUri(), note);
355
        }
356

357
        if (!aborted) {
358
            // Submit all tasks except the "meta" task
359
            if (timestamp != null) {
360
                if (new Date().getTime() - timestamp.getTimeInMillis() < THIRTY_DAYS) {
361
                    if (FeatureFlags.last30dRepoEnabled()) {
362
                        runTask.accept(() -> loadNanopubToLatest(allStatements));
×
363
                    }
364
                }
365
            }
366

367
            if (FeatureFlags.textRepoEnabled()) {
368
                runTask.accept(() -> loadNanopubToRepo(np.getUri(), textStatements, "text"));
×
369
            }
370
            if (FeatureFlags.fullRepoEnabled()) {
371
                runTask.accept(() -> loadNanopubToRepo(np.getUri(), allStatements, "full"));
×
372
            }
373
            // Note: "meta" task is deferred until all other tasks complete successfully
374

375
            runTask.accept(() -> loadNanopubToRepo(np.getUri(), allStatements, "pubkey_" + Utils.createHash(el.getPublicKeyString())));
×
376
            //                loadNanopubToRepo(np.getUri(), textStatements, "text-pubkey_" + Utils.createHash(el.getPublicKeyString()));
377
            for (IRI typeIri : NanopubUtils.getTypes(np)) {
378
                // Exclude locally minted IRIs:
379
                if (typeIri.stringValue().startsWith(np.getUri().stringValue())) continue;
380
                if (!typeIri.stringValue().matches("https?://.*")) continue;
381
                runTask.accept(() -> loadNanopubToRepo(np.getUri(), allStatements, "type_" + Utils.createHash(typeIri)));
×
382
                //                        loadNanopubToRepo(np.getUri(), textStatements, "text-type_" + Utils.createHash(typeIri));
383
            }
384
            //                for (IRI creatorIri : SimpleCreatorPattern.getCreators(np)) {
385
            //                        // Exclude locally minted IRIs:
386
            //                        if (creatorIri.stringValue().startsWith(np.getUri().stringValue())) continue;
387
            //                        if (!creatorIri.stringValue().matches("https?://.*")) continue;
388
            //                        loadNanopubToRepo(np.getUri(), allStatements, "user_" + Utils.createHash(creatorIri));
389
            //                        loadNanopubToRepo(np.getUri(), textStatements, "text-user_" + Utils.createHash(creatorIri));
390
            //                }
391
            //                for (IRI authorIri : SimpleCreatorPattern.getAuthors(np)) {
392
            //                        // Exclude locally minted IRIs:
393
            //                        if (authorIri.stringValue().startsWith(np.getUri().stringValue())) continue;
394
            //                        if (!authorIri.stringValue().matches("https?://.*")) continue;
395
            //                        loadNanopubToRepo(np.getUri(), allStatements, "user_" + Utils.createHash(authorIri));
396
            //                        loadNanopubToRepo(np.getUri(), textStatements, "text-user_" + Utils.createHash(authorIri));
397
            //                }
398

399
            for (Statement st : invalidateStatements) {
400
                runTask.accept(() -> loadInvalidateStatements(np, el.getPublicKeyString(), st, pubkeyStatement, pubkeyStatementX));
×
401
            }
402

403
            // Wait for all non-meta tasks to complete successfully before submitting the meta task
404
            for (var task : runningTasks) {
405
                try {
406
                    task.get();
407
                } catch (ExecutionException | InterruptedException ex) {
408
                    throw new RuntimeException("Error in nanopub loading thread", ex.getCause());
409
                }
410
            }
411

412
            // Now submit and wait for the "meta" task after all other tasks have completed successfully
413
            Future<?> metaTask = loadingPool.submit(() -> loadNanopubToRepo(np.getUri(), metaStatements, "meta"));
×
414
            try {
415
                metaTask.get();
416
            } catch (ExecutionException | InterruptedException ex) {
417
                throw new RuntimeException("Error in nanopub loading thread (meta task)", ex.getCause());
418
            }
419
        }
420
    }
421

422
    private static Long lastUpdateOfLatestRepo = null;
6✔
423
    private static long THIRTY_DAYS = 1000L * 60 * 60 * 24 * 30;
6✔
424
    private static long ONE_HOUR = 1000L * 60 * 60;
6✔
425

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

480
    @GeneratedFlagForDependentElements
481
    private static void loadNanopubToRepo(IRI npId, List<Statement> statements, String repoName) {
482
        boolean success = false;
483
        int retries = 0;
484
        while (!success) {
485
            RepositoryConnection conn = TripleStore.get().getRepoConnection(repoName);
486
            try (conn) {
487
                // Serializable, because write skew would cause the chain of hashes to be broken.
488
                // The inserts must be done serially.
489
                conn.begin(IsolationLevels.SERIALIZABLE);
490
                var repoStatus = fetchRepoStatus(conn, npId);
491
                if (repoStatus.isLoaded) {
492
                    log.info("Already loaded: {}", npId);
493
                } else {
494
                    String newChecksum = NanopubUtils.updateXorChecksum(npId, repoStatus.checksum);
495
                    conn.remove(NPA.THIS_REPO, NPA.HAS_NANOPUB_COUNT, null, NPA.GRAPH);
496
                    conn.remove(NPA.THIS_REPO, NPA.HAS_NANOPUB_CHECKSUM, null, NPA.GRAPH);
497
                    conn.add(NPA.THIS_REPO, NPA.HAS_NANOPUB_COUNT, vf.createLiteral(repoStatus.count + 1), NPA.GRAPH);
498
                    // @ADMIN-TRIPLE-TABLE@ REPO, npa:hasNanopubCount, NANOPUB_COUNT, npa:graph, admin, number of nanopubs loaded
499
                    conn.add(NPA.THIS_REPO, NPA.HAS_NANOPUB_CHECKSUM, vf.createLiteral(newChecksum), NPA.GRAPH);
500
                    // @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)
501
                    conn.add(npId, NPA.HAS_LOAD_NUMBER, vf.createLiteral(repoStatus.count), NPA.GRAPH);
502
                    // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasLoadNumber, LOAD_NUMBER, npa:graph, admin, the sequential number at which this NANOPUB was loaded
503
                    conn.add(npId, NPA.HAS_LOAD_CHECKSUM, vf.createLiteral(newChecksum), NPA.GRAPH);
504
                    // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasLoadChecksum, LOAD_CHECKSUM, npa:graph, admin, the checksum of all loaded nanopubs after loading the given NANOPUB
505
                    conn.add(npId, NPA.HAS_LOAD_TIMESTAMP, vf.createLiteral(new Date()), NPA.GRAPH);
506
                    // @ADMIN-TRIPLE-TABLE@ NANOPUB, npa:hasLoadTimestamp, LOAD_TIMESTAMP, npa:graph, admin, the time point at which this NANOPUB was loaded
507
                    conn.add(statements);
508
                }
509
                conn.commit();
510
                success = true;
511
            } catch (Exception ex) {
512
                log.warn("Could not load nanopub to repo.", ex);
513
                if (conn.isActive()) conn.rollback();
514
            }
515
            if (!success) {
516
                retries++;
517
                if (retries >= MAX_RETRIES) {
518
                    throw new RuntimeException("Failed to load nanopub " + npId + " to repo " + repoName + " after " + MAX_RETRIES + " retries");
519
                }
520
                long delay = computeBackoffMillis(retries);
521
                log.info("Retrying in {} ms (attempt {}/{})...", delay, retries, MAX_RETRIES);
522
                try {
523
                    Thread.sleep(delay);
524
                } catch (InterruptedException x) {
525
                    Thread.currentThread().interrupt();
526
                }
527
            }
528
        }
529
    }
530

531
    private record RepoStatus(boolean isLoaded, long count, String checksum) {
×
532
    }
533

534
    /**
535
     * To execute before loading a nanopub: check if the nanopub is already loaded and what is the
536
     * current load counter and checksum. This effectively batches three queries into one.
537
     * This method must be called from within a transaction.
538
     *
539
     * @param conn repo connection
540
     * @param npId nanopub ID
541
     * @return the current status
542
     */
543
    @GeneratedFlagForDependentElements
544
    private static RepoStatus fetchRepoStatus(RepositoryConnection conn, IRI npId) {
545
        var result = conn.prepareTupleQuery(QueryLanguage.SPARQL, REPO_STATUS_QUERY_TEMPLATE.formatted(npId)).evaluate();
546
        try (result) {
547
            if (!result.hasNext()) {
548
                // This may happen if the repo was created, but is completely empty.
549
                return new RepoStatus(false, 0, NanopubUtils.INIT_CHECKSUM);
550
            }
551
            var row = result.next();
552
            return new RepoStatus(row.hasBinding("loadNumber"), Long.parseLong(row.getBinding("count").getValue().stringValue()), row.getBinding("checksum").getValue().stringValue());
553
        }
554
    }
555

556
    @GeneratedFlagForDependentElements
557
    private static void loadInvalidateStatements(Nanopub thisNp, String thisPubkey, Statement invalidateStatement, Statement pubkeyStatement, Statement pubkeyStatementX) {
558
        boolean success = false;
559
        int retries = 0;
560
        while (!success) {
561
            List<RepositoryConnection> connections = new ArrayList<>();
562
            RepositoryConnection metaConn = TripleStore.get().getRepoConnection("meta");
563
            try {
564
                IRI invalidatedNpId = (IRI) invalidateStatement.getObject();
565
                // Basic isolation because here we only read append-only data.
566
                metaConn.begin(IsolationLevels.READ_COMMITTED);
567

568
                Value pubkeyValue = Utils.getObjectForPattern(metaConn, NPA.GRAPH, invalidatedNpId, NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY);
569
                if (pubkeyValue != null) {
570
                    String pubkey = pubkeyValue.stringValue();
571

572
                    if (!pubkey.equals(thisPubkey)) {
573
                        //log.info("Adding invalidation expressed in " + thisNp.getUri() + " also to repo for pubkey " + pubkey);
574
                        connections.add(loadStatements("pubkey_" + Utils.createHash(pubkey), invalidateStatement, pubkeyStatement, pubkeyStatementX));
575
//                                                connections.add(loadStatements("text-pubkey_" + Utils.createHash(pubkey), invalidateStatement, pubkeyStatement));
576
                    }
577

578
                    for (Value v : Utils.getObjectsForPattern(metaConn, NPA.GRAPH, invalidatedNpId, NPX.HAS_NANOPUB_TYPE)) {
579
                        IRI typeIri = (IRI) v;
580
                        // TODO Avoid calling getTypes and getCreators multiple times:
581
                        if (!NanopubUtils.getTypes(thisNp).contains(typeIri)) {
582
                            //log.info("Adding invalidation expressed in " + thisNp.getUri() + " also to repo for type " + typeIri);
583
                            connections.add(loadStatements("type_" + Utils.createHash(typeIri), invalidateStatement, pubkeyStatement, pubkeyStatementX));
584
//                                                        connections.add(loadStatements("text-type_" + Utils.createHash(typeIri), invalidateStatement, pubkeyStatement));
585
                        }
586
                    }
587

588
//                                        for (Value v : Utils.getObjectsForPattern(metaConn, NPA.GRAPH, invalidatedNpId, DCTERMS.CREATOR)) {
589
//                                                IRI creatorIri = (IRI) v;
590
//                                                if (!SimpleCreatorPattern.getCreators(thisNp).contains(creatorIri)) {
591
//                                                        //log.info("Adding invalidation expressed in " + thisNp.getUri() + " also to repo for user " + creatorIri);
592
//                                                        connections.add(loadStatements("user_" + Utils.createHash(creatorIri), invalidateStatement, pubkeyStatement));
593
//                                                        connections.add(loadStatements("text-user_" + Utils.createHash(creatorIri), invalidateStatement, pubkeyStatement));
594
//                                                }
595
//                                        }
596
                }
597

598
                metaConn.commit();
599
                // TODO handle case that some commits succeed and some fail
600
                for (RepositoryConnection c : connections) c.commit();
601
                success = true;
602
            } catch (Exception ex) {
603
                log.warn("Could not load invalidate statements.", ex);
604
                if (metaConn.isActive()) metaConn.rollback();
605
                for (RepositoryConnection c : connections) {
606
                    if (c.isActive()) c.rollback();
607
                }
608
            } finally {
609
                metaConn.close();
610
                for (RepositoryConnection c : connections) c.close();
611
            }
612
            if (!success) {
613
                retries++;
614
                if (retries >= MAX_RETRIES) {
615
                    throw new RuntimeException("Failed to load invalidate statements for " + thisNp.getUri() + " after " + MAX_RETRIES + " retries");
616
                }
617
                long delay = computeBackoffMillis(retries);
618
                log.info("Retrying in {} ms (attempt {}/{})...", delay, retries, MAX_RETRIES);
619
                try {
620
                    Thread.sleep(delay);
621
                } catch (InterruptedException x) {
622
                    Thread.currentThread().interrupt();
623
                }
624
            }
625
        }
626
    }
627

628
    @GeneratedFlagForDependentElements
629
    private static RepositoryConnection loadStatements(String repoName, Statement... statements) {
630
        RepositoryConnection conn = TripleStore.get().getRepoConnection(repoName);
631
        // Basic isolation: we only append new statements
632
        conn.begin(IsolationLevels.READ_COMMITTED);
633
        for (Statement st : statements) {
634
            conn.add(st);
635
        }
636
        return conn;
637
    }
638

639
    @GeneratedFlagForDependentElements
640
    static List<Statement> getInvalidatingStatements(IRI npId) {
641
        List<Statement> invalidatingStatements = new ArrayList<>();
642
        boolean success = false;
643
        int retries = 0;
644
        while (!success) {
645
            RepositoryConnection conn = TripleStore.get().getRepoConnection("meta");
646
            try (conn) {
647
                // Basic isolation because here we only read append-only data.
648
                conn.begin(IsolationLevels.READ_COMMITTED);
649

650
                TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT * { graph <" + NPA.GRAPH + "> { " + "?np <" + NPX.INVALIDATES + "> <" + npId + "> ; <" + NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY + "> ?pubkey . " + "} }").evaluate();
651
                try (r) {
652
                    while (r.hasNext()) {
653
                        BindingSet b = r.next();
654
                        invalidatingStatements.add(vf.createStatement((IRI) b.getBinding("np").getValue(), NPX.INVALIDATES, npId, NPA.GRAPH));
655
                        invalidatingStatements.add(vf.createStatement((IRI) b.getBinding("np").getValue(), NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY, b.getBinding("pubkey").getValue(), NPA.GRAPH));
656
                    }
657
                }
658
                conn.commit();
659
                success = true;
660
            } catch (Exception ex) {
661
                log.warn("Could not load invalidating statements.", ex);
662
                if (conn.isActive()) conn.rollback();
663
            }
664
            if (!success) {
665
                retries++;
666
                if (retries >= MAX_RETRIES) {
667
                    throw new RuntimeException("Failed to get invalidating statements for " + npId + " after " + MAX_RETRIES + " retries");
668
                }
669
                long delay = computeBackoffMillis(retries);
670
                log.info("Retrying in {} ms (attempt {}/{})...", delay, retries, MAX_RETRIES);
671
                try {
672
                    Thread.sleep(delay);
673
                } catch (InterruptedException x) {
674
                    Thread.currentThread().interrupt();
675
                }
676
            }
677
        }
678
        return invalidatingStatements;
679
    }
680

681
    @GeneratedFlagForDependentElements
682
    private static void loadNoteToRepo(Resource subj, String note) {
683
        boolean success = false;
684
        int retries = 0;
685
        while (!success) {
686
            RepositoryConnection conn = TripleStore.get().getAdminRepoConnection();
687
            try (conn) {
688
                List<Statement> statements = new ArrayList<>();
689
                statements.add(vf.createStatement(subj, NPA.NOTE, vf.createLiteral(note), NPA.GRAPH));
690
                conn.add(statements);
691
                success = true;
692
            } catch (Exception ex) {
693
                log.warn("Could not load note to repo.", ex);
694
            }
695
            if (!success) {
696
                retries++;
697
                if (retries >= MAX_RETRIES) {
698
                    throw new RuntimeException("Failed to load note to repo for " + subj + " after " + MAX_RETRIES + " retries");
699
                }
700
                long delay = computeBackoffMillis(retries);
701
                log.info("Retrying in {} ms (attempt {}/{})...", delay, retries, MAX_RETRIES);
702
                try {
703
                    Thread.sleep(delay);
704
                } catch (InterruptedException x) {
705
                    Thread.currentThread().interrupt();
706
                }
707
            }
708
        }
709
    }
710

711
    static boolean hasValidSignature(NanopubSignatureElement el) {
712
        try {
713
            if (el != null && SignatureUtils.hasValidSignature(el) && el.getPublicKeyString() != null) {
24!
714
                return true;
6✔
715
            }
716
        } catch (GeneralSecurityException ex) {
3✔
717
            log.warn("Signature validation failed for signature element {}", el.getUri(), ex);
18✔
718
        }
3✔
719
        return false;
6✔
720
    }
721

722
    private static IRI getBaseTrustyUri(Value v) {
723
        if (!(v instanceof IRI)) return null;
9!
724
        String s = v.stringValue();
9✔
725
        if (!s.matches(".*[^A-Za-z0-9\\-_]RA[A-Za-z0-9\\-_]{43}([^A-Za-z0-9\\\\-_].{0,43})?")) {
12✔
726
            return null;
6✔
727
        }
728
        return vf.createIRI(s.replaceFirst("^(.*[^A-Za-z0-9\\-_]RA[A-Za-z0-9\\-_]{43})([^A-Za-z0-9\\\\-_].{0,43})?$", "$1"));
21✔
729
    }
730

731
    // TODO: Move this to nanopub library:
732
    private static boolean isIntroNanopub(Nanopub np) {
733
        for (Statement st : np.getAssertion()) {
33✔
734
            if (st.getPredicate().equals(NPX.DECLARED_BY)) return true;
21✔
735
        }
3✔
736
        return false;
6✔
737
    }
738

739
    /**
740
     * Detects whether the given nanopub is a Space-defining nanopub (typed
741
     * {@code gen:Space}) and, if so, registers each space it declares (one per
742
     * {@code <spaceIri> gen:hasRootDefinition <rootUri>} triple) in
743
     * {@link SpaceRegistry}. Nanopubs missing the {@code gen:hasRootDefinition}
744
     * triple are not recognized as space-defining — there is no transition fallback.
745
     *
746
     * @param np the nanopub to inspect
747
     * @return the set of space refs registered from this nanopub (possibly empty);
748
     *         currently used by tests to assert detection behavior. Production
749
     *         callers invoke this for its side effect on {@link SpaceRegistry};
750
     *         downstream consumers (extraction, materialization) follow in later
751
     *         steps of #62.
752
     */
753
    static Set<String> detectAndRegisterSpaces(Nanopub np) {
754
        if (!FeatureFlags.spacesEnabled()) return Collections.emptySet();
6!
755
        boolean isSpaceTyped = false;
6✔
756
        for (IRI typeIri : NanopubUtils.getTypes(np)) {
33✔
757
            if (typeIri.equals(GEN.SPACE)) {
12✔
758
                isSpaceTyped = true;
6✔
759
                break;
3✔
760
            }
761
        }
3✔
762
        if (!isSpaceTyped) return Collections.emptySet();
12✔
763
        Set<String> spaceRefs = new LinkedHashSet<>();
12✔
764
        for (Statement st : np.getAssertion()) {
33✔
765
            if (!st.getPredicate().equals(GEN.HAS_ROOT_DEFINITION)) continue;
18✔
766
            if (!(st.getSubject() instanceof IRI spaceIri)) continue;
27!
767
            if (!(st.getObject() instanceof IRI rootUri)) continue;
27!
768
            String rootNanopubId = TrustyUriUtils.getArtifactCode(rootUri.stringValue());
12✔
769
            if (rootNanopubId == null || rootNanopubId.isEmpty()) {
15!
770
                log.warn("Ignoring space {}: gen:hasRootDefinition target is not a trusty URI: {}", spaceIri, rootUri);
15✔
771
                continue;
3✔
772
            }
773
            SpaceRegistry.Registration registration = SpaceRegistry.get().registerSpace(rootNanopubId, spaceIri);
15✔
774
            spaceRefs.add(registration.spaceRef());
15✔
775
            if (registration.wasNew()) {
9!
776
                SpacesAdminStore.persistSpace(rootNanopubId, spaceIri);
9✔
777
            }
778
        }
3✔
779
        return spaceRefs;
6✔
780
    }
781

782
    /**
783
     * Check if a nanopub is already loaded in the admin graph.
784
     *
785
     * @param npId the nanopub ID
786
     * @return true if the nanopub is loaded, false otherwise
787
     */
788
    @GeneratedFlagForDependentElements
789
    static boolean isNanopubLoaded(String npId) {
790
        boolean loaded = false;
791
        RepositoryConnection conn = TripleStore.get().getRepoConnection("meta");
792
        try (conn) {
793
            if (Utils.getObjectForPattern(conn, NPA.GRAPH, vf.createIRI(npId), NPA.HAS_LOAD_NUMBER) != null) {
794
                loaded = true;
795
            }
796
        } catch (Exception ex) {
797
            log.warn("Could not check whether nanopub is loaded.", ex);
798
        }
799
        return loaded;
800
    }
801

802
    private static ValueFactory vf = SimpleValueFactory.getInstance();
6✔
803

804
    // TODO remove the constants and use the ones from the nanopub library instead
805

806
    /**
807
     * Template for the query that fetches the status of a repository.
808
     */
809
    // Template for .fetchRepoStatus
810
    private static final String REPO_STATUS_QUERY_TEMPLATE = """
84✔
811
            SELECT * { graph <%s> {
812
              OPTIONAL { <%s> <%s> ?loadNumber . }
813
              <%s> <%s> ?count ;
814
                   <%s> ?checksum .
815
            } }
816
            """.formatted(NPA.GRAPH, "%s", NPA.HAS_LOAD_NUMBER, NPA.THIS_REPO, NPA.HAS_NANOPUB_COUNT, NPA.HAS_NANOPUB_CHECKSUM);
6✔
817
}
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